Jamie Hartnoll
Jamie Hartnoll

Reputation: 7341

Getting "Change" event for a text field whose contents is changed by jQuery

I've made some pretty checkboxes using some pretty simple jQuery

HTML

<span class="iconElement checkBox" id="update_Check"></span>
<input type="text" id="update" name="update" value="0" class="hidden savedData" />

JS

$('.checkBox').live('click', function (e) { 
    if ($(this).hasClass('disabled') != true) {
        $(this).toggleClass('checked')
        var thisValue = parseInt($(this).next().val());
        var newValue = (thisValue - 1) * (-1); // enusures the output is either 1 or 0, [ (1-1)*-1=0 and (0-1)*-1 =1 ]
        $(this).next().val(newValue);
    };
}); 

This is simply a span with a nice CSS background sprite, which when clicked changes toggles it's "checked" class, adjusting the CSS sprite from a "Tick" to an empty box. At the same time it also changes the content of a text field (hidden by CSS class 'hidden') to a 1 or a 0 to indicate whether the box is checked.

It has to have this 1 or 0 as when the data is passed to the next stage I have to have a value, an unchecked checkbox sends no value.

This all works fine!

BUT... I also need to be able to detect the "change" event of the hidden text field.

This is to be controlled by the "savedData" class.

$('.savedData').live('change', function () {
    // do stuff now we know this has been changed
});

I could of course include this within the "click" event in the code above, but that's not practical for the application.

It seems that the "change" even is only trigger by elements which are changed by the keyboard or mouse, anything changed by jQuery is not being flagged.

Initially I was using hidden input type and thought that was the issue, but have changed them all to text type now and the problem is still there!

Any tips?!

Upvotes: 2

Views: 1150

Answers (1)

lonesomeday
lonesomeday

Reputation: 237875

It seems that the "change" even is only trigger by elements which are changed by the keyboard or mouse, anything changed by jQuery is not being flagged.

Yes, that is correct. That is precisely how this works. Only changes made by the user trigger event handlers: programmatic changes do not. The only way to trigger them is to do so yourself:

$(this).next().val(newValue).change();

The .change() triggers a change event on the element, so the handler will be called.

Upvotes: 3

Related Questions