jquery add value to dynamically created input text field

Skittles picture Skittles · Jul 20, 2015 · Viewed 20.6k times · Source

I have a set of dynamically create input text boxes created via jQuery ajax and need to populate certain fields with values. I am using this;

$('#priority').attr('value', tplData);

but that does not seem to be working.

I tried .val(tplData), but to no avail.

Is there a different way to set the values of fields, via jQuery, that have been created dynamically?

The input field html is as follows;

<div class="field-container">
  <!-- This field is being dynamically created via an ajax call using jQuery -->
  <input type="text" name="priority" id="priority" class="input-group vert-spacer-bottom" placeholder="Priority">
</div>

Many thanks in advance.

EDIT It seems to definitely be something with dynamically create elements, because if I create the input element statically in the HTML and try these suggestions, it works perfect. But if the input fields are created dynamically, no dice.

Answer

Siamak Ferdos picture Siamak Ferdos · Jul 20, 2015

Try:

$('body').find('#priority').attr('value', tplData);

EDIT : It should be work, however you can do this too:

$('body').find('name=["priority"]').val(tplData);
$('body').find('#priority').val(tplData);

EDIT: See this on jsfiddle