zhiyuan zhiyuan - 6 months ago 15
jQuery Question

JQuery can't select the value from input that created dynamically

What I want to do is to add multiple inputs into this div which has id "addedRoles". It first like this:

<div id="addedRoles" class="form-group">
<div class="col-md-10">
<input class="addedRole form-control" type="text" name="newRoleNames" />
</div>
</div>


And I added more divs using these codes:

$('#btnAddNewRole').click(function (event) {
$('#addedRoles').append(
'<div class="col-md-10">'
+ '<input class="addedRole form-control" type="text" name="newRoleNames" />'
+ '</div>');
});


After that, I was trying to select values from all inputs but all I got is the value from the first hardcode input. Is it because the inputs were created dynamically? How to get value from them all? Thanks

Answer

For dynamically added element .click() doesn't fire. Plus add some class to your textbox. Id should be unique throughout the DOM.

For dynamically added element you should .on in either way.

$(document).on('click','.txtboxClass',function (e) 
{
  //do stuff here
  var userInput = $(this).val();
});

OR

  $('.txtboxClass').on('click',function (e) 
 {
  //do stuff here
  var userInput = $(this).val();
 });

If you find adding class an overhead, thats not a big issue you can do using attribute selector as well.

Comments