tags:

views:

26

answers:

2

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>

http://jsfiddle.net/RM5wG/

+1  A: 

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>​
poezn
have you tested this script to work? http://jsfiddle.net/RM5wG/1/
ina
no :) it's before(), not prepend(), since prepend adds the content at the beginning of an element's content, while before adds it... well... before the element
poezn
+5  A: 

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);
});​

You can give it a try here

.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() :)

Nick Craver
You can also swap and use `.before`, IIRC.
strager
@strager - Yep that'd work the other way around, ideally you'd do `$('<label />', {for: this.id, id: this.id }).insertBefore(this)` if doing many elements, that's the reasoning for leaving it `.insertBefore()`, in case the OP incorporates his previous question as well :)
Nick Craver
@Nick Craver, Ah, okay. But your comment says `id: this.id`, which looks wrong. (I'm not familiar with the initializing jQuery syntax (whatever it's called.)
strager
@strager - Oops you're right, thinking of a previous question, for this it'd be `$('<label />', { 'for': this.id, text: this.id })`, (`for` needs quotes since it's a keyword), you can give it a try here: http://jsfiddle.net/3JQp9/
Nick Craver