0

I have created, dynamically, input text field when an option of multiple select list is selected. The problem is those input fields does not respond to events of Jquery.

Here is the code I used:

<form>
  Select from the multiple select menu to generate input fields<br>
    <select id="sel" multiple="multiple">
        <option value="1">Tomato</option>
        <option value="2">Banana</option>
        <option value="3">Apple</option>
        <option value="4">Orange</option>
    </select>
    <div id="panel">
    </div>
</form>
<script type="text/javascript">
if (!window.jQuery) alert('Jquery is missing');
$(document).ready(function() {
    var e = new Array();
    $("#sel").change(function(event) {
        str = '';       
        $( "#sel option:selected" ).each(function() {
            //str += $( this ).val() + " ";
            //"+$( this ).val()+"           
            i = $(this).index();
            str += "<input title='"+i+"' type='text' value='"+((e[i])? e[i]: '')+"' name='n'><br />"
        });
        $( "#panel" ).html( str );
    });

    $('input').change(function(event) {
        alert('hi');
    });

});
</script>
<br />
<hr />
<input value="sdsd" type="text" /> This is orginally created and works fine, but the generated above do not work with change event

This is an online working DEMO.

SaidbakR
  • 11,955
  • 16
  • 89
  • 173
  • Use the jQuery delegate method. It works for the dynamically created element. – naresh kumar Mar 22 '14 at 00:52
  • @nareshkumar What is jQuery delegate method? – SaidbakR Mar 22 '14 at 00:54
  • Ok here is the jQuery official sites documentation link. http://api.jquery.com/delegate/ – naresh kumar Mar 22 '14 at 00:56
  • 1
    If you want event handlers to automatically apply to dynamically created DOM elements, then you need to use delegated event handling which you can read about [here](http://stackoverflow.com/questions/8752321/jquery-live-vs-on-method-for-adding-a-click-event-after-loading-dynamic-ht/8752376#8752376), [here](http://stackoverflow.com/questions/9730277/jquery-event-handlers-whats-the-best-method/9730309#9730309) and [here](http://stackoverflow.com/questions/9814298/does-jquery-on-work-for-elements-that-are-added-after-the-event-handler-is-cre/9814409#9814409). – jfriend00 Mar 22 '14 at 01:08
  • Ok thank you all. `$('#panel').on("click", "input", function() {alert('hi')});` is working fine now. – SaidbakR Mar 22 '14 at 01:17
  • 1
    This is a dup of many questions/answers that came before including the ones mentioned in my previous comment. – jfriend00 Mar 22 '14 at 01:19

0 Answers0