简体   繁体   中英

How to get last selected radio button id

I have two UL lists with some radio buttons. Now I want to get last selected radio button ID attribute form their UL .

For example:

  • If I selected radio button from first UL then return selected radio ID .
  • If I selected radio button from second UL then return seledted radio ID .

I have tried bellow code but not working properly. If you try with selecting first radio button from first UL you will get alert with selected ID , but when you selected radio button from second UL you will get alert from first UL and that I dont want. :(

I want to get last checked radio button ID from that UL .

Any idea how to do this?

Can you please check with this way:

  • First select 20 from first UL you will get 20.
  • Second select 80 from second UL you will get 80.

Now again change radio button from first UL and that changed radio ID I want.

Here is my JSFiddle .

Thanks.

 $("#update_cart").click(function() { var radioID = $("input[type='radio']:checked").attr("id"); if (radioID) { alert(radioID); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script> <ul class="one"> <li> <label for="1" class="label_check"> <input type="radio" id="1" name="one" value="10">10 </label> </li> <li> <label for="2" class="label_check"> <input type="radio" id="2" name="one" value="20">20 </label> </li> <li> <label for="3" class="label_check"> <input type="radio" id="3" name="one" value="30">30 </label> </li> <li> <label for="4" class="label_check"> <input type="radio" id="4" name="one" value="40">40 </label> </li> <li> <label for="5" class="label_check"> <input type="radio" id="5" name="one" value="50">50 </label> </li> </ul> <ul class="two"> <li> <label for="6" class="label_check"> <input type="radio" id="6" name="two" value="40">60 </label> </li> <li> <label for="7" class="label_check"> <input type="radio" id="7" name="two" value="70">70 </label> </li> <li> <label for="8" class="label_check"> <input type="radio" id="8" name="two" value="100">80 </label> </li> <li> <label for="9" class="label_check"> <input type="radio" id="9" name="two" value="120">90 </label> </li> <li> <label for="10" class="label_check"> <input type="radio" id="10" name="two" value="120">100 </label> </li> </ul> <input type="button" id="update_cart" class="update_cart" value="Update Cart"> 

Use

$("#update_cart").click(function () {
  var radioID = $("input[type='radio'].active").attr("id");
  if (radioID) {
      alert(radioID);
  }
});

$("input[type='radio']").click(function(){
  $('.active').removeClass('active');
     $(this).addClass('active');
});

Working Demo

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM