cpcdev cpcdev - 2 months ago 12
Javascript Question

Radio button value not correct in IE after second click.. working in other browsers

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 + '"><span class="radio' + (this.checked ? ' radio-checked' : '') + '"></span></a>').insertAfter(this);
});
$('.radio-fx').on('click', function (e) {
$("input[name=travel_mode]").removeAttr("checked"); // add this line
$check = $(this).prev('input:radio');
var unique = '.' + this.className.split(' ')[1] + ' span';
$(unique).attr('class', 'radio');
$(this).find('span').attr('class', 'radio-checked');
this.blur();
this.focus();
$check.attr('checked', true);
getDirections();
}).on('keydown', function (e) {
if ((e.keyCode ? e.keyCode : e.which) == 32) {
$(this).trigger('click');
}
});
});


This code works fine in all browsers except IE. In IE, after the second click of a radio button the value is "undefined".

I tried using:

this.blur();
this.focus();


as per other suggestions but that did not work.

How can I fix this to work in IE also?

Here is the fiddle

Answer

use prop instead of attr

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