Reputation: 425
I am dynamically inserting new html text inputs through a button, however when i create them and assign an ID, it assigns the ID to the H4 text and label, but not the actual input element. I'm using Jquery to create the elements..
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.attr("id", "targetname" + counter)
.insertBefore("#elementtarget");
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' /></label>")
.attr("id", "targetreturn" + counter)
.insertBefore("#elementtarget");
I know that the input is technically a child, but if i try to set the attribute of the child the H4 text disappears.
Upvotes: 0
Views: 223
Reputation: 4937
How about setting the id on the html string?
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' id='targetreturn" + counter + "'/></label>")
.insertBefore("#elementtarget");
PS: remember to parse the input fields before submitting; otherwise you will not get your data... ...or set also the "name" on the input field :p
Upvotes: 0
Reputation: 33870
That's because of the order of your chaining. If you find and add attribute before appending it to the DOM, you'll end up adding only the input (because of the find).
Just append the element then change your id :
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Return :</h4><label><span>Return :</span><input type='text' value='' /></label>")
.insertBefore("#elementtarget")
.find('input')
.attr("id", "targetreturn" + counter);
Upvotes: 0
Reputation: 1074335
I know that the input is technically a child...
Nothing "technical" about it, it's a child. You can still set its id
, though:
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.find("input").attr("id", "targetname" + counter).end()
.insertBefore("#elementtarget");
(And similarly for the next block.) There, after creating the structure, I use .find("input")
to find the input
within it, then assign the id
, then use end
so we get back to the original jQuery object (the h4
and its descendants) so we can use insertBefore
on it.
Alternately, you could add the id
after inserting the structure:
$("<h4><span style=\"color: #006085\">Target " + counter + ":</span> Enter Name :</h4><label><span>Name :</span><input type='text' value='' /></label>")
.insertBefore("#elementtarget")
.find("input").attr("id", "targetname" + counter);
...which means you don't need end()
anymore.
Upvotes: 4