cpcdev cpcdev - 2 months ago 7
Javascript Question

incorrect radio value eventually shown.. can't figure out why

I am using some code to display radio buttons as images:

HTML:

<div id="skin_1" title="Walk">
<input type="radio" name="travel_mode" id="mode_walking" value="WALKING" /><br>
Walk
</div>

<div id="skin_2" title="Drive">
<input type="radio" name="travel_mode" id="mode_driving" value="DRIVING" /><br>
Drive
</div>

<div id="skin_3" title="Bike">
<input type="radio" name="travel_mode" id="mode_bicycle" value="BICYCLING" /><br>
Bike
</div>

<div id="skin_4" title="Transit">
<input type="radio" name="travel_mode" id="mode_transit" value="TRANSIT" /><br>
Transit
</div>

<div>
<a href="#" onClick="testMe();">What mode is selected?</a>
</div>


JS:

$(function () {
$('input:radio').hide().each(function () {
var label = $("label[for=" + '"' + this.id + '"' + "]").text();
$('<a ' + (label != '' ? 'title=" ' + label + ' "' : '') + ' class="radio-fx ' + this.name + '" href="#"><span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('.radio-fx').on('click', function (e) {
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
$check.attr('checked', true);
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});


Problem:

Eventually after changing the radio button and clicking "What mode is selected?" enough times the WRONG radio button value is alerted.

Question:

How can I get the correct value of the radio button every time?

Here is the fiddle: Live Fiddle Here

Answer

I just added one line to clear all the checkbox:

$('.radio-fx').on('click', function (e) {
   $("input[name=travel_mode]").removeAttr("checked"); // add this line
   .....

Full Fiddle

Comments