John John - 1 month ago 11
HTML Question

On input event on form doesn't fire when checkbox changes

The title pretty much say it all. To reiterate, when I have the listener

.on('input',...
assigned to a form, the event fires for
<select>
and
<input>
changes, but it doesn't fire for checkbox changes.

Here's a fiddle of what I'm talking about:

https://jsfiddle.net/6vzftzum/

<form class='request-form'>
<input type='text'>
<select>
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<label><input type="checkbox" name="not-completed" checked>Not Completed</label>
</form>

<div class='put-stuff-in-here'>

</div>




var i=0;
$(".request-form").on('input', function() {

$(".put-stuff-in-here").append(i + "<br>");
i++;

});


Is there a way I can make a listener that will fire for all input changes in a form?

Answer

Your input event won't fire the checkboxes, but we can handle it with a change event. Although we'll need to separate the listeners, we can have them call a mutual function so that any changes that need to be made to both only have to happen in one place.

function changeFunction(elem) {
    $(".put-stuff-in-here").append(i + "<br>");
    i++;
}

$('.request-form input[type="checkbox"], .request-form select').change(function() {
    changeFunction($(this));
});

$('.request-form input[type="text"]').on('input', function() {
    changeFunction($(this));
});

JSFiddle