mtwallet
mtwallet

Reputation: 5086

jQuery - Loop through Label/Input pairs and add unique ID

I have the following code placed multiple times across a page some in a table and some in a tooltip:

<p class="radioBtn">
    <label for="business"></label>
    <input id="business" type="radio" name="radioBtn" value="" />
</p>
<p class="radioBtn">    
    <label for="private"></label>
    <input id="private" type="radio" name="radioBtn" value="" />
</p>

I would like to know how, with jQuery I can loop through the entire page and add a unique ID number on to the end of the label 'for' attribute and also the input 'id' so I would end up with something unique for each pairing like this:

<p class="radioBtn">
    <label for="business0"></label>
    <input id="business0" type="radio" name="radioBtn" value="" />
</p>
<p class="radioBtn">    
    <label for="private0"></label>
    <input id="private0" type="radio" name="radioBtn" value="" />
</p>

Many thanks in advance.

Upvotes: 2

Views: 5726

Answers (3)

user113716
user113716

Reputation: 322502

Late answer, but using jQuery, I'd probably do it more like this:

$("input:radio[name=radioBtn]").attr('id',function(index,id){
    $(this).prev()[0].htmlFor += index;
    return id += index;
});

Less code and likely better performance.

To explain, .attr() can accept a function for the value you're setting. Its return value will be the new value of the attribute.

In the function, the first parameter is the index of the current item in the iteration, the second parameter is the current value of the attribute being set (the id in this case).

So the function body goes like this:

  • $(this).prev() Get the previous element using jQuery's .prev().
  • [0] Pull the DOM element out of the jQuery object. (the <label>)
  • Set the label's htmlFor property to += the current index.
  • Return the current id += the current index.

Upvotes: 3

rahul
rahul

Reputation: 187050

Try

$(function(){
    $("input:radio[name='radioBtn']").each(function(index){
        var currElem = $(this);
        var prevLabel = currElem.prev();
        currElem.attr("id", this.id + index);

        prevLabel.attr("for", prevLabel.attr("for") + index);
    });    
});

See a working demo

Upvotes: 1

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124778

Something like this:

$('label').each(function(index) {
    var forAttr = $(this).attr('for');
    $next = $(this).next();
    if($next.attr('id') == forAttr) {
        $(this).attr('for', forAttr + index);
        $next.attr('id', forAttr + index);
    }
});

Though it would be better to do this on the server side.

Upvotes: 1

Related Questions