0

I have a small script problem with jQuery. I tried to make a form with 2 radio buttons and a select list. I want that if the user clicks on the list it would check the "email" and the radio should get checked if the user click on the radio "livredor", I need to make it "autochecked".

This code only works once. If the radio buttons get clicked it's stuck.

$("#destinataires").change(function() {
  $('input[type=radio][name=choix][value=email]').attr('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<INPUT id="emailchoix" name="choix" type="radio" value="email">

<SELECT id="destinataires" name="contact" size="1">
    <option value="etienne">Étienne</option>
    <option value="michele">Michèle</option>
    <option value="thomas">Thomas</option>
    <option value="filou">Filou</option>
    <option value="mustapha">Mustapha</option>
</SELECT>

<INPUT id="livrechoix" type="radio" name="choix" value="livredor"> Livredor
Jonas
  • 121,568
  • 97
  • 310
  • 388
zipzap
  • 1

1 Answers1

0

I recommend using jQuery's prop() to set the checked state, instead of attr().
According to the documentation for prop():

Properties generally affect the dynamic state of a DOM element without changing the serialized HTML attribute. Examples include the value property of input elements, the disabled property of inputs and buttons, or the checked property of a checkbox. The .prop() method should be used to set disabled and checked instead of the .attr() method.

$("#destinataires").change(function() {
  $('input[type=radio][name=choix][value=email]').prop('checked', true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="emailchoix" name="choix" type="radio" value="email">

<select id="destinataires" name="contact" size="1">
    <option value="etienne">Étienne</option>
    <option value="michele">Michèle</option>
    <option value="thomas">Thomas</option>
    <option value="filou">Filou</option>
    <option value="mustapha">Mustapha</option>
</select>

<input id="livrechoix" type="radio" name="choix" value="livredor" checked> Livredor

For a more technical explanation, see .prop() vs .attr().

showdev
  • 28,454
  • 37
  • 55
  • 73