简体   繁体   中英

how to capture change event in input with jquery?

$('input').change(function(){
    alert($(this).val());
});
$('input').val(1);

This dont work. I need capture the change input with JavaScript:-s

Thanks.

Programmatic changes to <input> elements don't cause events. Only user interaction does.

You can do this however:

$('input').val(1).trigger('change');

You have to put those functions inside the "Ready" function. see the fiddle: http://jsfiddle.net/SfjJQ/1/

$(function() {
    $('input').change(function() {
        alert($(this).val());
    });
    $('input').val(1);
    $('input').trigger('change');
});​

keep in mind that your:

$('input').val(1);

initializes the input to have a value of 1.

Of course you could also do this:

$(function() {
    $('input')
        .change(function() {
            alert($(this).val());
        })
        .val(1)
        .trigger('change');
});​

As others have mentioned, .val() does not trigger any events; however, you could add a wrapper function to jQuery that will change the value and trigger the event if wanted:

$( function () {

    //-- new jQuery function
    $.fn.changeVal = function () {
        $.fn.val.apply( this, arguments );
        $( this ).trigger( 'change' );
    };

    //-- your updated code
    $('input').change(function(){
        alert($(this).val());
    });
    $('input').changeVal(1);

} );​

http://jsfiddle.net/bA3V2/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM