Question

So I have a text field:

number of weeks <div id = "weekcount"><input type="text" id="numweeks" name="numweeks" value="" class = "dialog_inputfield" /></div><br />

And a Javascript function that checks if the value changes in that text field at any point:

$('#numweeks').keyup(function(event) {
        var date = $('#datepicker').val();
        var numWeeks = $('#numweeks').val();
        change(calculate(date, numWeeks));
});

And that works fine. But I used innerHTML to change the div with the id "weekcount" to contain another textfield, and I changed it back to the original text field with:

document.getElementById('weekcount').innerHTML = '<input type="text" id="numweeks" name="numweeks"  value="" class = "dialog_inputfield" />'

After that the keyup no longer works, even though the id is the same as it was before. Is there something I'm doing wrong? Thanks.

Was it helpful?

Solution

You're currently binding directly to the DOM element, but that gets replaced by your innerHTML assignment, thereby also losing the event binding (it's a new DOM element).

What you want is to use a delegated ("live") event. Have a look at the jQuery on function, it unifies nicely all event handling patterns.

$('#weekcount').on('keyup', '#numweeks', function(event) {
        var date = $('#datepicker').val();
        var numWeeks = $('#numweeks').val();
        change(calculate(date, numWeeks));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top