Axel Stone
Axel Stone

Reputation: 1580

jQuery keeps getting value of wrong radio button if checked by default

Radio buttons, the first one is checked by default:

  <div class="shipping">
    <div class="title">Select shipping method</div>
    <label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
    <label><input type="radio" name="shipping" value="personal">Personal pick up</label>
    <button>Next</button>
  </div>

Js:

$(document).on('click', '.shipping button', function() {
  let val = $('.shipping').find('input[name="shipping"]:checked').val()
  console.log(val);
}

Even if I manually switch the radio buttons and select the second one, jQuery keeps getting the value of the first radio button, independently on user selection.

Why is that? I can't find solution.

Upvotes: 1

Views: 209

Answers (1)

Anurag Srivastava
Anurag Srivastava

Reputation: 14413

Edit 2: Added JS code from updated question. It seems to work here.

Edit: Added submit button to demonstrate submit action.


Well, are you calling console.log after changing the value? I created a snippet below and it works fine.

$(function() {
  let val = $('.shipping').find('input[name="shipping"]:checked').val()
  console.log(val);

  /*$('#btn').on('click', function() {
    let val = $('.shipping').find('input[name="shipping"]:checked').val()
    console.log(val);
  })*/

  $(document).on('click', '.shipping button', function() {
    let val = $('.shipping').find('input[name="shipping"]:checked').val()
    console.log(val);
  })
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shipping">
  <div class="title">Select shipping method</div>
  <label><input type="radio" name="shipping" value="courier-dpd" checked="checked">Courier DPD</label>
  <label><input type="radio" name="shipping" value="personal">Personal pick up</label>
  <button>Next</button>
</div>

Upvotes: 1

Related Questions