Phillip Senn
Phillip Senn

Reputation: 47605

Firing an change event from JavaScript

I have:

<input name="X">

and in JavaScript:

$('input').on('change','[name=X]',function() {
        $('body').append('on change fired!');
    }
);
$('input[name=X]').change(function() {
    $('body').append('change fired!');
});
$(input[name='X']).val('test');

But my problem is that neither change event gets fired.

Upvotes: 0

Views: 79

Answers (3)

Hazem Salama
Hazem Salama

Reputation: 15111

You are missing quotes around your selector, plus how about adding trigger?

$("input[name='X']").val("test").trigger("change");

The fiddle

Upvotes: 4

Selvakumar Arumugam
Selvakumar Arumugam

Reputation: 79830

Changing the value of an input element programatically will not trigger any event. Alternatively, You can call .change after .val like below,

$('input[name=X]').val('test').change();

Edit: Also fixed the missing quotes around the input selector.

DEMO: http://jsfiddle.net/G6n4h/1/

Upvotes: 1

Gabe
Gabe

Reputation: 50493

Make sure you're using a ready block

jsFiddle

$(function(){
   $('input').on('change','[name=X]',function() {
        $('body').append('on change fired!');
   });
   $('input[name=X]').change(function() {
       $('body').append('change fired!');
   });
   $(input[name='X']).val('test'); 
});

​ If you're trying to simply trigger is programmatically:

$('input[name=X]').change(); // trigger change event

Upvotes: 1

Related Questions