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

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

Thanks.

1
  • Your question is unclear. The "change" handler you've got is fine, assuming you're calling it at an appropriate time (i.e., in a <script> tag after all the <input> elements on the page, or inside a "ready" or "load" handler). I interpreted your question as being about the fact that the call to .val() does not trigger the "change" handler. Commented Apr 4, 2012 at 14:57

3 Answers 3

8

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

You can do this however:

$('input').val(1).trigger('change');
Sign up to request clarification or add additional context in comments.

3 Comments

He's asking how to capture the event, not how to throw it :)
@mattytommo the problem is that there is no event created when you programmatically change the value of an element like that. The "change" event handler already there is fine for catching the event.
Ah I see, I didn't realise he's trying to throw the event himself, my bad. +1 for you :)
2

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');
});​

3 Comments

No event is triggered by the call to .val().
My interpretation of the question is that Mr. User expected the call to .val(1) to trigger the "change" handler. I could be wrong; the question is sparse and enigmatic.
yeah i see what you mean, I added another line to trigger the change event at page load.
1

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.