Jquery add value to dynamically generated text input field

I have a set of dynamically generating text input fields created with jQuery ajax and need to fill certain fields with values. I am using this:

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

      

but that doesn't seem to work.

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

Is there any other way to set field values, via jQuery, that were generated dynamically?

The html input field looks like this:

<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>

      

Thank you very much in advance.

EDIT It seems that there is definitely something with dynamic element creation, because if I create an input element statically in HTML and try these suggestions, it works great. But if the input fields are dynamically created, there are no cubes.

+3


source to share


4 answers


So, after further banging my head against the wall of notorious code, I was able to come up with a solution that ended up being great!

The dynamically generated textbox now accepts a value assignment from my jquery code. The magic was to rethink how the element should be seen by jquery in terms of code visibility.

First of all, keep in mind that the DIV container is static and is always present in the document. This means that whatever is created in this DIV will always always be on the client side. After locking down the client side system, I thought jQuery needed to be aware of the newly created elements. This was achieved with the following code:



var inputElm = '';
inputElm += '<input type="' + data.type + '" name="' + data.name + '" id="' + data.name + '" class="' + data.name + ' input-group vert-spacer-bottom" placeholder="' + data.placeholder + '" />';

$('.field-container').after().html(inputElm);

      

Now when I execute the code ... it works fine and sets the value of the input textbox to the desired value.

0


source


Try:

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

      

EDIT : This should be a job, however you can do this too:



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

      

EDIT: See this on jsfiddle

+2


source


First of all, is your textbox created before you assign a value to it. You can check if there is any error in the console tab. It sometimes happens that an error has occurred before your code fails. Right Click on Page-> Check Item → Console. If any errors are then resolved and try again.

you can try: $ ('# priority'). val (tplData)

0


source


If you have multiple controls you need to use the class

$(".priority").prop("value",tplData);

      

check for errors in the console.

0


source







All Articles