How to check if the radio camera was checked after it was pressed?

I have a click listener on my radio exchanges.

I need to check if the radio object has already been checked before clicking, or if it was not.

$('.GridRadio').live('click', function () { alert($(this).is(':checked')); }); 

However, the above warnings are true every time. How can I check if it was checked before it was clicked?

+4
source share
2 answers

You can use data() to store the previous value of the radio, and then check the current value for this:

 $(".GridRadio").click(function() { var lastValue = $(this).data("last-value"); var value = $(this).val(); if (lastValue == value) { alert("Already checked"); } else { alert("Not previously checked"); } $(".GridRadio").data("last-value", ""); $(this).data("last-value", value); }); 

Script example

If you set the checked attribute on one of the radio stations in HTML when the page loads, add this code to set the data for this particular one:

 $(".GridRadio:checked").data("last-value", $(".GridRadio:checked").val()) 
+5
source

If you use live , you will probably add $('.GridRadio') after $(document).ready . if it’s right, you can do this check when you add it. then when pressed, it will always be a negative value.

(and if it is on the page from the very beginning - you can perform this check after reloading the page before someone clicks on it.)

0
source

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


All Articles