Reputation: 1145
I'm trying to cancel a radio button click. I have a jquery click handler like this:
$("#myList").on("click","input", function(){
return false;
});
This works fine when there is already a selected value. But if I click a radio button from a group that has no selected value, the return false does not work, and the element that I clicked actually gets selected.
Any clues?
Edit:
Here is the fiddle demonstrating the problem:
Edit2:
Just found out this only happens on chrome :( Firefox and IE work as expected. Maybe a workaround?
Upvotes: 4
Views: 3482
Reputation: 6480
Here, try this JS_FIDDLE-DEMO
It detects the click on the parent container. Not the radio button it self.
//listen to click on parent div,span,li for example.
$("#myList-parent").click(function(){
alert('You clicked radio!');
//Now put your logic here. I decide based on the radio button value.
if($('input:radio[name=type]:checked').val() == "UnSelectable"){
alert($('input:radio[name=type]:checked').val());
return false;
}
});
Update (work around for Chrome): JS-FIDDLE-DEMO
It seems Chrome has issues with on click
so replace it with on mousedown
(or use both?):
$("input").on("mousedown",function(e) {
e.preventDefault();
if ($(this).is(':checked')) {
alert('This radio button was checked in mousedown');
} else {
alert('This radio button was not checked in mousedown');
}
});
Upvotes: 2
Reputation: 85545
Use change methods for input elements instead of click.
$("#myList").on("change","input", function(e){
if(something){
e.preventDefault();
} else{
//for test
alert('not true');
}
});
Upvotes: 1