Remove checked property from a radiobutton

1

Why do you always think of yourself as an employee? My intention is to remove the checked attribute but I can not get it.

I looked this thread and I think I do it as the solution proposes, but it does not work for me.

$(document).ready(function() {

  $('.radio').click(function() {
    if ($('#radio-Empleado').is(':checked')) {
      $('#radio-Cliente').removeAttr('checked');
      alert('Soy empleado');
    } else if ($('#radio-Cliente').is(':checked')) {
      $('#radio-Empleado').removeAttr('checked');
      alert('Soy cliente');
    } else {
      // Si los ninguno de los dos está selecionado
      alert('Ningún radiobutton seleccionado');
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="Contenedores">
  <h2> Define si eres empleado o cliente</h2>

  <div id="Cont-Select-EmpCli">
    <input type="radio" class="radio" id="radio-Empleado">
    <label for="radio-Empleado">Empleado</label>

    <input type="radio" class="radio" id="radio-Cliente">
    <label for="radio-Cliente">Ciente</label>
  </div>
</div>

Cheers!

    
asked by NEA 25.02.2018 в 14:42
source

1 answer

3

The proposed code is wrong on several levels:

To begin with, what you want to remove is a property, not an attribute. You should use .removeProp('checked') or .prop('checked', false) . You can see the difference between both in What is the difference between attr and prop in jQuery?

Secondly, do not check which radio has been pressed, simply look if the employee is "checked" and, if it is not, look at the client. Therefore, if employee is already marked, it does not matter if I clicked on the client or not, the values are never changed.

Thirdly, you do not need any code, it's enough that both radio buttons have the same name so that only one of them can be pressed:

<label>Cliente</label>
<input type="radio" name="test" value="cliente">
<label>Empleado</label>
<input type="radio" name="test" value="empleado">
    
answered by 25.02.2018 в 15:02