简体   繁体   中英

Jquery input Event doesn't fire

I am trying to add this to an input field so whenever a user types or pastes something, an alert appears on the webpage. But it doesn't fire('code' is the id of the inputfield):

var codeInput = document.getElementById('code');
    $('#code').on('input', function () {
        window.alert(codeInput.value);
    });

Assuming your html is ok this will work:

$('#code').on('input', function () {
    alert($(this).val())
});

I say assuming because if the html is dynamic you may need a different approach, like this:

$(document).on('input', '#code', function () {
    alert($(this).val())
});

Have a look at this fiddle

var codeInput = document.getElementById('code');

This line, when encountered while execution of the JavaScript, will get the reference to the element with id code and store it in codeInput. This value will NOT update once it has been assigned.

$('#code').on('input', function () {
        window.alert(codeInput.value);
    });

This is an event handler. After it has been registered once, it will be executed everytime element code will have an input.

But you are trying to alert the value of codeInput , which has been assigned a value before, AND NOT UPDATED .

This should work (Get the reference to the current state of the element, and then call its value)

$('#code').on('input', function () {
    alert($(this).val())
});

jQuery does not have input event, you can use below code

var codeInput = document.getElementById('code');
    $('#code').on('input', function () {
        window.alert(codeInput.value);
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM