Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery getting label for checked checkbox

In my below code, I keep getting "MexicoMexico" returned as the label text when I check "Mexico". For all the other fields I am not getting this duplicate result, it is only for this one field. The issue occurs immediately after the first assignment of countryvalues[i] and I don't see why.

<div id="country">
....
   <li><input type="checkbox" name="country" value="mexico" class="checkbox">
   <label for="mexico">Mexico</label></input></li>
</div>

countryvalues = $('#country input:checkbox:checked').map(function() {
    return this.value;
}).get(); 
for (var i=0; i<countryvalues.length; i++)
    {
        countryvalues[i] = $("label[for='" + countryvalues[i] + "']").text();
        countryvalues[i] = countryvalues[i].split(' ').join('%20');
        fields = fields + "coveraa!";
        url = url + countryvalues[i] + "!";
    }
like image 621
sarina Avatar asked Apr 08 '13 05:04

sarina


2 Answers

If you have multiple li . then you can use this code to get the checked checkbox label text.

JS FIDLLE LINK

<div id="country">
....
   <li><input type="checkbox" name="country" value="mexico" class="checkbox">
   <label for="mexico">Mexico</label></input>
    </li>
    <li><input type="checkbox" name="country" value="mexico" class="checkbox">
   <label for="mexico">Canada</label></input>
    </li>
</div>


$(document).ready(function(){
    $('#country li input:checkbox').change(
        function() {
            //alert('HI');
            alert($(this).next('label').text());
                   }
    );
});
like image 31
rahularyansharma Avatar answered Nov 09 '22 02:11

rahularyansharma


Sarina, I can only suggest you try obtaining the string you seek within the .map() callback rather than looping again with for(...){...}.

var countryvalues = $('#country input:checkbox:checked').map(function() {
    return $(this).next("label").text().split(' ').join('%20');
}).get();

Make sure the HTML is purged of all instances of </input> and that the input elements are self-closed, <input ... />.

like image 56
Beetroot-Beetroot Avatar answered Nov 09 '22 02:11

Beetroot-Beetroot