Radio button the same message always comes out

1

Why is it always 'I am employed'? How is it done to act according to the selected radio button?

$(document).ready(function() {

  $('.EmpCli').change(function() {
    var valor = $('.EmpCli').val;

    if (valor = 'empleado') {
      alert('soy Empleado');
    } else if (valor = 'cliente') {
      alert('soy cliente');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>Cliente</label>
<input type="radio" name="EmpCli" class="EmpCli" value="cliente">

<label>Empleado</label>
<input type="radio" name="EmpCli" class="EmpCli" value="empleado">
    
asked by NEA 28.02.2018 в 22:46
source

2 answers

2

You have several errors:

val is a method, not a property, so the parentheses are missing to retrieve the value of the element

You should take the value of the marked item ( :checked )

Comparisons of values in JavaScript are not done with an equal symbol ( = ), if not with two ( == ) or, better, with three to make a strict comparison ( === ):

$(document).ready(function() {

  $('.EmpCli').change(function() {
    var valor = $('.EmpCli:checked').val();

    if (valor === 'empleado') {
      alert('soy Empleado');
    } else if (valor === 'cliente') {
      alert('soy cliente');
    }
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<label>Cliente</label>
<input type="radio" name="EmpCli" class="EmpCli" value="cliente">

<label>Empleado</label>
<input type="radio" name="EmpCli" class="EmpCli" value="empleado">
    
answered by 28.02.2018 / 22:53
source
1

You have a basic syntax problem. Remember that for conditional IF and compare a value must be done with double sign of equal "==", in terms of obtaining the radius that was changed if you must change your code a bit.

$(document).ready(function() {

  $('.EmpCli').change(function() {
    var valor = $(this).val();  // Se obtiene el 'value' del radio que llama al evento change

    if (valor == 'empleado') {   // Doble signo de igual ==
      alert('soy Empleado');
    } else if (valor == 'cliente') {   // Doble signo de igual ==
      alert('soy cliente');
    }
  });

});

If you need to check that the item is "checked" or "marked" you can do the following:

if ($(this).is(":checked")) {
  alert("Marcado");
}
    
answered by 28.02.2018 в 23:02