I wonth to be able to uncheck radio button on second click with custom design radio buttons.
Here is HTML code:
<input type="radio" id="sortForm11" name="sortForm11" value="descPrice"/>
<label for="sortForm11">Text<span ></span></label>
Here is CSS code:
input[type="radio"] {
display:none;
}
input[type="radio"] + label span {
display:inline-block;
width: 20px;
height: 20px;
margin: 0 10px 0 0;
vertical-align:middle;
background:url(../images/checkbox.png) left top no-repeat;
background-size: 20px 20px;
cursor:pointer;
border-radius: 2px;
float:right;
}
input[type="radio"]:checked + label span {
background-color: #4bc2ff;
}
Here is js code:
$('input[name=sortForm11]').on('click',function () {
var $radio = $(this);
// if this was previously checked
if ($radio.data('waschecked') == true)
{
console.log('cao');
$radio.prop('checked', false);
$radio.data('waschecked', false);
}
else
$radio.data('waschecked', true);
// remove was checked from other radios
$radio.siblings('input[name=sortForm11]').data('waschecked', false);
});
PS : If my input field is visible and if I test this it is working but if I tweak it for custom design it doesn't work.
You can use this example: https://jsfiddle.net/k0sp350f/5/
$('input[name=sortForm11] + label span').on('click', function (e) {
var $radio = $(this).parent().prev();
// if this was previously checked
if ($radio.is(':checked')) {
$radio.removeAttr('checked');
} else {
$('input[name=' + $radio.attr('name') + ']').removeAttr('checked');
$radio.attr('checked', 'checked');
}
});
Unchecking it works too!
UPDATED: For multiple radio buttons with the same name
<input type="radio" id="sortForm11" name="sortForm11" value="descPrice"/>
<label for="sortForm11">Text<span ></span></label>
<br>
<input type="radio" id="sortForm11" name="sortForm12" value="descPrice"/>
<label for="sortForm12">Text2<span ></span></label>
var val = 0;
var val2 = 0;
$('input[name=sortForm11]').on("click", function(){
console.log(val);
if($(this).val()==val)
{$(this).prop('checked', false);
val = -1;
}
else val = $(this).val();
});
var val2 = 0;
$('input[name=sortForm12]').on("click", function(){
console.log(val2);
if($(this).val()==val2)
{$(this).prop('checked', false);
val2 = -1;
}
else val2 = $(this).val();
});
Use the following code.
var val = 0;
$('input[name=sortForm11]').on("click", function(){
console.log(val);
if($(this).val()==val)
{$(this).prop('checked', false);
val = -1;
}
else val = $(this).val();
});
Here is example : http://jsfiddle.net/wuAWn/534/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.