When you click on LI, then automatically press on the input radio station

When you click on li, I want the input radio to be pressed.

However, I get an error from the conole log:

Uncaught RangeError: Maximum call stack size exceeded 

How to fix it?

Here's the html code:

  <ul class="Method"> <li class="shipping_today active"> <label> Label 1 </label> <input value="shipping_today" name="shipping" type="radio" /> </li> <li class="shipping_next_month"> <label> Label 2 </label> <input value="shipping_next_month" name="shipping" type="radio" /> </li> </ul> 

Jquery:

 $(".Method li").click(function() { var thisLi = $(this); var radio = $(this).find("input:radio"); if (radio.val() == "shipping_today") { $(".Method li").eq(1).removeClass("active"); $(this).addClass("active"); } if (radio.val() == "shipping_next_month") { $(".Method li").eq(-2).removeClass("active"); $(this).addClass("active"); } radio.click(); //problem here... }); 

Is my jQuery code good? what can be improved?

thanks.

+4
source share
3 answers

Which is an endless loop because the click event that you fire on the radio button bubbles up to the <li> element and invokes the handler to execute recursively.

One solution would be to only pass the click event if it does not belong to the switch itself:

 $(".Method li").click(function(event) { var thisLi = $(this); var radio = $(this).find("input:radio"); // [...] if (radio[0] !== event.target) { radio.click(); } }); 

If you only want to check the switch, event relaying is not required. You can use prop () instead:

 radio.prop("checked", true); 
+7
source

To prevent bubbling of events, you can use stopPropagation ():

 $(".Method li").click(function(evt) { evt.stopPropagation(); ... }); 
0
source

Your code needs settings, try the following:

 $(".Method li").click(function() { var thisLi = $(this); var radio = $(this).find("input:radio"); if (radio.val() == "shipping_today") { $(".Method li").eq(1).removeClass("active"); thisLi.addClass("active"); radio.attr("checked", true); } else if (radio.val() == "shipping_next_month") { $(".Method li").eq(0).removeClass("active"); thisLi.addClass("active"); radio.attr("checked", true); } }); 

You can put radio.attr () only once unconditionally if all LI tags contain radio buttons.

0
source

All Articles