mvasco
mvasco

Reputation: 5101

Getting undefined value for radio button input

In a form I have following radio button input:

<div class="form-group col-sm-12">
  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_1" value="Efectivo" checked>Efectivo
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_2" value="Tarjeta">Tarjeta
    </label>
  </div>

I am trying to get the selected value as follows:

var forma_pago = $("#opciones input:radio:checked").val();
alert (forma_pago);

But I am getting as result "Undefined"

what is wrong there?

Upvotes: 1

Views: 6070

Answers (5)

user2560539
user2560539

Reputation:

alert ($("input[name=opciones]:checked").val());
$("input[name=opciones]").on('click',function() {
alert ($(this).val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-12">
  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_1" value="Efectivo" checked>Efectivo
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_2" value="Tarjeta">Tarjeta
    </label>
  </div>

Upvotes: 0

webdevanuj
webdevanuj

Reputation: 675

try this:

alert($('input[type="radio"]:checked').val());

Upvotes: 0

KevBot
KevBot

Reputation: 18898

You do not have an element with the id of opciones. If you still want to be specific, use the attribute equals selector instead:

var forma_pago = $("input[name='opciones']:radio:checked").val();
console.log(forma_pago);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group col-sm-12">

  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_1" value="Efectivo" checked>Efectivo
    </label>
  </div>
  <div class="radio">
    <label>
      <input type="radio" name="opciones" id="opciones_2" value="Tarjeta">Tarjeta
    </label>
  </div>

Upvotes: 1

Roxoradev
Roxoradev

Reputation: 893

try this

 var forma_pago = $("input[name=opciones]:checked").val();
    alert (forma_pago);

Upvotes: 1

Ibrahim Khan
Ibrahim Khan

Reputation: 20740

Your selector is wrong. opciones is name not id. Try like following.

var forma_pago = $(":radio[name=opciones]:checked").val();
alert(forma_pago);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="radio">
  <label>
    <input type="radio" name="opciones" id="opciones_1" value="Efectivo" checked>Efectivo
  </label>
</div>
<div class="radio">
  <label>
    <input type="radio" name="opciones" id="opciones_2" value="Tarjeta">Tarjeta
  </label>
</div>

Upvotes: 3

Related Questions