Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery on Input not working on dynamically inserted value

I'm trying to alert a value using jquery when it is generated from a javascript code, the value is generated on the input box the problem is jquery cannot detect the changes, commands i tested are "change, input" but when i manually input a value jquery triggers

sample code:

value is dynamically generated on the javascript and pushed / inserted to the inputbox, the value is not manually generated javascript:

document.getElementById("displayDID").value = DisplayName ;

html:

<input type="text" id="displayDID" />

jquery:

$('#displayDID').on("input" ,function() {
            var work = $(this).val();
            alert(work);
        });

the value of the id="displayDID" changes but jquery cannot detect it after execution.

sample fiddle http://jsfiddle.net/SU7bU/1/

like image 547
user3261755 Avatar asked Feb 14 '14 10:02

user3261755


2 Answers

add trigger to it

$('#gen').on('click',function() {
    $('#field').val('val').trigger("change");
});


$(document).on("change",'#field' ,function() {
    var work = $(this).val();
    alert(work);

});

http://jsfiddle.net/ytexj/

like image 182
ah-shiang han Avatar answered Nov 12 '22 00:11

ah-shiang han


It is because you have added the script before input is ready.Due to which, event is not getting set on that element.write the code on document ready:

$(document).ready(function(){
 $('#displayDID').on("input" ,function() {
        var work = $(this).val();
        alert(work);
    });
})

or use event delegation:

$(document).on("input",'#displayDID' ,function() {
        var work = $(this).val();
        alert(work);
    });
like image 22
Milind Anantwar Avatar answered Nov 12 '22 00:11

Milind Anantwar