Reputation: 129
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] + "!";
}
Upvotes: 5
Views: 25064
Reputation: 371
Check the below example and you get the script how to get label of checkbox in jQuery
<html>
<body>
<ul>
<li>
<input type="checkbox" name="mouse" value="1" id="mouse" /><label for="mouse">Mouse</label>
</li>
<li>
<input type="checkbox" name="keyboard" value="1" id="keyboard" /><label for="mouse">Keyboard</label>
</li>
<li>
<input type="checkbox" name="monitor" value="1" id="monitor" /><label for="mouse">Monitor</label>
</li>
</ul>
</body>
</html>
<script type="text/javascript">
var label = jQuery('label[for=' + jQuery(this).attr('id') + ']').html();
alert(label);
</script>
Code taken from here : http://chandreshrana.blogspot.in/2015/09/how-to-get-checkbox-label-text-jquery.html
Upvotes: 0
Reputation: 18078
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 ... />
.
Upvotes: 7
Reputation: 10755
If you have multiple li
. then you can use this code to get the checked checkbox
label text.
<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());
}
);
});
Upvotes: 1