simple jquery trim input down to 2 characters

397
December 10, 2016, at 1:53 PM

I'm wanting to take whatever is entered into input and when the button is clicked, it removes everything after the first two characters that were entered.

For example if I entered in "BT2J43" I would like it to cut it down to "BT" in the input field is the possible?

Here's my fiddle below, I'm just learn jquery, go easy on me!

https://jsfiddle.net/ktd9gbu9/1/

$("#submit123").click(function() {
  $("#text123").text($("#text123")[0].innerText.substr(2));
});
<input type="search" name="table_filter" id="text123" required>
<input name="submit" type="Submit" id="submit123" value="Search">
Answer 1

You want to use .val() instead of .text():

$("#submit123").click(function () {
    $("#text123").val($("#text123").val().substr(0, 2));
});

jsFiddle example

Also with substr() you forgot the starting index.

Answer 2

You can do that easily but you need to target .val()

Here is a clean code that may help you! :)

$("#button").click(function () {
    var search = $("#search");
    search.val(search.val().substr(0, 2));
});

There you go with JSfiddle Example

Rent Charter Buses Company
READ ALSO
Run jQuery after all content on page is loaded in angularjs

Run jQuery after all content on page is loaded in angularjs

I have a directive where I am including some jQuery like this:

390
Ajax to php file error

Ajax to php file error

I am getting a very generic error message from an Ajax calls xhr parameter

407
Jquery Mobile Panel not working after update

Jquery Mobile Panel not working after update

The following code was working fine in previous jquery mobile versionsAfter update the panel does not open after switching pages more than twice

396