Jherek Carnelian Jherek Carnelian - 7 months ago 8
Javascript Question

jquery: Don't get why element selector work or don't work

I have an html document with the following element

<input type="text" style="width: 40px;" name="rate" id="rate" value="1" />


Now I want to use jQuery to run a function once this textfield is changed. But I seem not to understand how the selectors work. Because this example works:

<script>
// works
$(document).on('input', function() {
alert();
});
</script>


But of course it fires on all inputs that are interacted. So I only want a certain id to response:

<script>
// doesn't work
$(document).on('#rate', function() {
alert();
});
</script>


But it doesn't work. Neither does it with class or attributes ("input[name='rate']") nor with 'input#rate' instead of document.

$('input#rate').on(function() {


Why is that?

jQuery included in head is:

<script src="/assets/jquery-1.12.3.min.js"></script>

Answer

on() accepts the event name as the first argument.

As there is no event called #rate, the following will not work.

$(document).on('#rate', function() {

Use

$(document).on('keyup', '#rate', function() {
               ^^^^^^^                         : Event name here
Comments