mvasco mvasco - 5 months ago 8
Javascript Question

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?

Answer

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>

Comments