Event for $ ('input [type = radio]: checked')

This is my jQuery script:

$("input[type=radio]:checked").live("click", function() { $(this).attr("checked",false); }); 

I want all my switches to be able to be checked and removed. The code should run ONLY when checking the radio. But somehow, any click on the radio (whether it is installed or not) triggers this event. It is as if the browser first checked the radio and then ran my script.

If I alert($("input[type=radio]:checked").size()) , it gave me the correct score.

I am testing code in FF4, but I hope the solution can serve IE.

Well, since my question seems confusing, this is working code for what I want, but it requires an additional custom attribute, which I hope can avoid.

 <input type="radio" name="group1" value="1" isChecked="false"/> <input type="radio" name="group1" value="2" isChecked="false"/> <input type="radio" name="group1" value="3" isChecked="false"/> <script> $(document).ready(function(){ $("radio").click(function(){ if($(this).attr("isChecked")=="false"){ $(this).attr("isChecked","true"); $(this).attr("checked",true); } else{ $(this).attr("isChecked","false"); $(this).attr("checked",false); } }); }); </script> 
+6
source share
1 answer

In fact, this does not mean that the radio buttons are intended for use. It looks like you are trying to create an input control that is between the switch and the checkbox.

There are several approaches you could take:

1) Use a separate button to clear the radio button:

HTML:

 <input id="clearRadios" type="button">Clear</input> 

jQuery:

 $('#clearRadios').click(function() { // use attr only if you're using an older version of jQuery $('input[type=radio]').prop('checked', false); }); 

2) Use the checkboxes equipped for operation as switches:

 var $chkboxes = $('input[type=checkbox]'); $chkboxes.click(function() { var currChkbox = this; $chkboxes.each(function() { if (this !== currChkbox) { $(this).prop('checked', false); } }); }); 

If it were me, I would probably go with the first option in most cases.

+7
source

Source: https://habr.com/ru/post/892637/


All Articles