Mr.Happy
Mr.Happy

Reputation: 2647

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:

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:

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">

Upvotes: 0

Views: 1414

Answers (1)

Milind Anantwar
Milind Anantwar

Reputation: 82241

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

Upvotes: 2

Related Questions