I’m fairly new to JQuery and I’m trying to add multiple form fields for example, <li id="container" id="add_field"><input type="text" name="text" value="text" /></li> but I think my JQuery code is off can some one please help me fix the JQuery code?
Here is the JQuery script.
var count = 0;
$(function(){
$('li#add_field').click(function(){
count += 1;
$('#container').append(
'<li><input id="field_' + count + '" name="fields[]' + '" type="text" /></li>' );
});
});
Here is the html code.
<form method="post" action="index.php">
<fieldset>
<ul>
<li><label for="code">Code: </label>
<textarea rows="8" cols="60" name="code" id="code"></textarea></li>
<li id="container" id="add_field"><input type="text" name="text" value="text" /></li>
<li><label for="comment">Comments: </label>
<textarea rows="8" cols="60" name="comment" id="comment"></textarea></li>
<li><input type="submit" name="submit" value="Submit" /></li></ul>
</fieldset>
</form>
.append() is going to insert your content at the end but inside the targeted element. In your example this will result in incorrectly nested
<li>elements.In your example I think you’re looking for .after() functionality. Each new element will be inserted at the top of the list which might not be preferable.
You can either put in conditional elements to test for placement using last(), or adjust your HTML and use append.
Perhaps something like this:
And as others have mentioned, you have two IDs on
<li id="container" id="add_field">. You should try to clean that up by either making one a class, or changing your HTML structure.