Reputation: 19534
Is it possible to use prepend
for each element in a list of input
's within a form
?
The prepend below only prepends the first element - is it possible to prepend the label for all items:
<script>
$(document).ready(function(){
$("#sg1").each(function(){
$(this).prepend("<label for=\""+$(this).attr("id")+"\">"+$(this).attr("id")+"</label>");
});
});
</script>
<form id="sg1">
<input name="member1" id="member1" value="jack" />
<input name="member2" id="member2" value="carter" />
<input name="member3" id="member3" value="jackson" />
<input name="member4" id="member4" value="tielk" />
</form>
Upvotes: 2
Views: 3897
Reputation: 4129
You just need to change the selector to the input elements within the #sg1 div:
<script>
$(document).ready(function(){
$("#sg1 input").each(function(){
$(this).before(""+$(this).attr("id")+"");
});
});
</script>
<form id="sg1">
<input name="member1" id="member1" value="jack" />
<input name="member2" id="member2" value="carter" />
<input name="member3" id="member3" value="jackson" />
<input name="member4" id="member4" value="tielk" />
</form>
Upvotes: 1
Reputation: 630379
You need to loop through the inputs instead of the form, and use something like .insertBefore()
instead, like this:
$("#sg1 input").each(function(){
$('<label for="'+ this.id +'">' + this.id + '</label>').insertBefore(this);
});
.prepend()
inserts an element as the first child, but an <input>
doesn't get children, if you want it before use .insertBefore()
to place it before the element you pass to .insertBefore()
:)
Upvotes: 7