[jquery] How do I implement onchange of <input type="text"> with jQuery?

<select> has this API. What about <input>?

This question is related to jquery input onchange

The answer is


As @pimvdb said in his comment,

Note that change will only fire when the input element has lost focus. There is also the input event which fires whenever the textbox updates without it needing to lose focus. Unlike key events it also works for pasting/dragging text.

(See documentation.)

This is so useful, it is worth putting it in an answer. Currently (v1.8*?) there is no .input() convenience fn in jquery, so the way to do it is

$('input.myTextInput').on('input',function(e){
 alert('Changed!')
});

$("input").keyup(function () {
    alert("Changed!");
});

If you want to trigger the event as you type, use the following:

$('input[name=myInput]').on('keyup', function() { ... });

If you want to trigger the event on leaving the input field, use the following:

$('input[name=myInput]').on('change', function() { ... });

You could simply work with the id

$("#your_id").on("change",function() {
    alert(this.value);
});

You could use .keypress().

For example, consider the HTML:

<form>
  <fieldset>
    <input id="target" type="text" value="Hello there" />
  </fieldset>
</form>
<div id="other">
  Trigger the handler
</div>

The event handler can be bound to the input field:

$("#target").keypress(function() {
  alert("Handler for .keypress() called.");
});

I totally agree with Andy; all depends on how you want it to work.


You can do this in different ways, keyup is one of them. But i am giving example below with on change.

$('input[name="vat_id"]').on('change', function() {
    if($(this).val().length == 0) {
        alert('Input field is empty');
    }
});

NB: input[name="vat_id"] replace with your input ID or name.


This worked for me. If field with name fieldA is clicked or any key entered it updates field with id fieldB.

jQuery("input[name='fieldA']").on("input", function() {
    jQuery('#fieldB').val(jQuery(this).val());
});

There is one and only one reliable way to do this, and it is by pulling the value in an interval and comparing it to a cached value.

The reason why this is the only way is because there are multiple ways to change an input field using various inputs (keyboard, mouse, paste, browser history, voiceinput etc.) and you can never detect all of them using standard events in a cross-browser environment.

Luckily, thanks to the event infrastructure in jQuery, it’s quite easy to add your own inputchange event. I did so here:

$.event.special.inputchange = {
    setup: function() {
        var self = this, val;
        $.data(this, 'timer', window.setInterval(function() {
            val = self.value;
            if ( $.data( self, 'cache') != val ) {
                $.data( self, 'cache', val );
                $( self ).trigger( 'inputchange' );
            }
        }, 20));
    },
    teardown: function() {
        window.clearInterval( $.data(this, 'timer') );
    },
    add: function() {
        $.data(this, 'cache', this.value);
    }
};

Use it like: $('input').on('inputchange', function() { console.log(this.value) });

There is a demo here: http://jsfiddle.net/LGAWY/

If you’re scared of multiple intervals, you can bind/unbind this event on focus/blur.


$("input").change(function () {
    alert("Changed!");
});

Here's the code I use:

$("#tbSearch").on('change keyup paste', function () {
    ApplyFilter();
});

function ApplyFilter() {
    var searchString = $("#tbSearch").val();
    //  ... etc...
}

<input type="text" id="tbSearch" name="tbSearch" />

This works quite nicely, particularly when paired up with a jqGrid control. You can just type into a textbox and immediately view the results in your jqGrid.


<input id="item123" class="firstName" type="text" value="Hello there" data-someattr="CoolExample" />

$(".firstName").on('change keyup paste', function () {
   var element = $(this);
   console.log(element);
   var dataAttribute = $(element).attr("data-someattr");
   console.log("someattr: " + dataAttribute );
});

I recommend use this keyword in order to get access to the entire element so your are able do everything you need with this element.


The following will work even if it is dynamic/Ajax calls.

Script:

jQuery('body').on('keyup','input.addressCls',function(){
  console.log('working');
});

Html,

<input class="addressCls" type="text" name="address" value="" required/>

I hope this working code will help someone who is trying to access dynamically/Ajax calls...


I would suggest using the keyup event something like below:

$('elementName').keyup(function() {
 alert("Key up detected");
});

There are a few ways of achieving the same result so I guess it's down to preference and depends on how you want it to work exactly.

Update: This only works for manual input not copy and paste.

For copy and paste I would recommend the following:

$('elementName').on('input',function(e){
 // Code here
});

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to input

Angular 4 - get input value React - clearing an input value after form submit Min and max value of input in angular4 application Disable Button in Angular 2 Angular2 - Input Field To Accept Only Numbers How to validate white spaces/empty spaces? [Angular 2] Can't bind to 'ngModel' since it isn't a known property of 'input' Mask for an Input to allow phone numbers? File upload from <input type="file"> Why does the html input with type "number" allow the letter 'e' to be entered in the field?

Examples related to onchange

Why can't I change my input value in React even with the onChange listener React Checkbox not sending onChange Set Label Text with JQuery android on Text Change Listener Jquery select change not firing onchange event on input type=range is not triggering in firefox while dragging select2 onchange event only works once Dropdown using javascript onchange How to fire a change event on a HTMLSelectElement if the new value is the same as the old? jQuery - on change input text