Reputation: 807
This is my jquery code....
$("#addinp").click(function() {
$(this).prepend('<label>Item ' + i + '<span class="small"></label><input type="text" name="middlename[]" />');
});
And this is my html....
<form id="form" name="form" method="post" action="?a=run">
<input type="text" name="firstname" id="firstname" />
<input type="text" name="lastname" id="lastname" />
<input type="text" name="middlename[]" id="middlename[]" />
<img src="add_another_name.png" id="addinp"/>
<button type="submit">Add</button>
</form>
This will not make another input appear before the "add another button" - The annoying this is if i do this...
$('form').prepend('<lab........
prepend it to the form it will work....... but the it will just not appear before the image...
Upvotes: 0
Views: 278
Reputation: 87073
Instead of prepend()
, try before()
as in the following, with valid HTML.
prepend()
will not work here because it inserts the passed element as a child of it at the beginning of target.
$("#addinp").click(function() {
$(this)
.before('<label>Item '+i+'<span class="small"></span></label><input type="text" name="middlename[]" />');
});
You can also use .insertBefore()
:
$("#addinp").click(function() {
$('<label>Item '+i+'<span class="small"></span></label><input type="text" name="middlename[]" />').insertBefore(this);
});
Don't forget to correct your above HTML.
Upvotes: 3
Reputation: 943650
From the manual:
The .prepend() method inserts the specified content as the first child of each element in the jQuery collection
You can't insert content as the first child of an image because the image can't have children.
You want before()
to insert the content before the image.
Upvotes: 2