3

I have a problem with .click() event in jquery. I create an input tag with a button, and then when I click this tag it must show an alert message. But it doesn't work. Here is the HTML code:

<div id="test">

</div>
<input type="button" id="btn" value="Submit" />

And the Jquery code:

$("#btn").click(function(){    
    html = "<input type='text' size='1' name='courses[]' value='1' />";
    $("#test").after(html);
});
$("input[type='text']").on("click", function(){             
    alert('ppp');

});

All libraries of jquery are linked in the real site. Here is an example in jsFiddle: http://jsfiddle.net/82pps6Lz/29/ Thanks

Bak
  • 242
  • 1
  • 3
  • 11
  • 3
    You'll have to use delegated binding -- [Direct vs. Delegated - jQuery .on()](http://stackoverflow.com/questions/8110934/direct-vs-delegated-jquery-on). The `` doesn't yet exist when `$("input[type='text']")` would be trying to find it. – Jonathan Lonowski Sep 02 '14 at 16:29

3 Answers3

7

Think, you insert a new <input> element only when you click on the button, but you bind a click event straight away, when the <input> element doesn't yet exist. So you either should bind the event after (or during) element insertion:

$('#btn').click(function(){    
    var html = "<input type='text' size='1' name='courses[]' value='1' />";
    $(html).on('click', function() {
        // ...
    }).insertAfter('#test');
});

... or use the DOM event delegation:

$('#btn').click(function(){    
    var html = "<input type='text' size='1' name='courses[]' value='1' />";
    $('#test').after(html);
});

$(document).on('click', 'input[type="text"]' function() {             
    // ...
});
VisioN
  • 132,029
  • 27
  • 254
  • 262
3

Use this:

$(document).on("click","input[type='text']", function(){             
    alert('ppp');
});

The above is how you use event-delegation. You can also bind after <input> exists.

DEMO

Community
  • 1
  • 1
Amit Joki
  • 53,955
  • 7
  • 67
  • 89
0

You need to bind the input after insertion. because when you perform $("input[type='text']") the input not exists. it exists until you click on submit.

      $("#btn").click(function(){    
           html = "<input type='text' size='1' name='courses[]' value='1' />";
           $("#test").after(html);
           $("input[type='text']").on("click", function(){             
                 alert('ppp');

           });
       });
levi
  • 19,165
  • 7
  • 56
  • 68