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] + "!";
}
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());
}
);
});
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 ... />
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With