Using single option with radio button

Asked

Viewed 5,707 times

1

I’m not being able to create a single option for radio button selection. When I click on two options, it selects both, when the ideal would be either one or the other.

			<div><label for="b_ant">Base Anterior</label><input name="b_ant" type="radio" value="S" /></div>
			<div><label for="b_grade">Base na Grade</label><input name="b_grade" type="radio" value="S" /></div>
			<div><label for="b_grade">Base em Veículos Novos</label><input name="b_novos" type="radio" value="S" /></div>

  • 2

    the Names shall be equal

2 answers

7

The name of the inputs must be the same. See the example below:

<div>
  <label>
    Base Anterior
    <input id="ant" name="base" type="radio" value="S" />
  </label>
</div>
<div>
  <label>
    Base na Grade
    <input id="grade" name="base" type="radio" value="S" />
  </label>  
</div>
<div>
  <label>
    Base em Veículos Novos
    <input id="novo" name="base" type="radio" value="S" />
  </label>
</div>
      
     

2


With pure HTML only as stated in my comment on your question os names devem ser iguais

When a RADIO option is checked, it will only be unchecked when another RADIO option with the same name is selected

If you need to keep different Ames, consider using jquery. example:

$(document).ready(function () {
    $('input[type=radio]').change(function() {
        $('input[type=radio]:checked').not(this).prop('checked', false);
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div><label for="b_ant">Base Anterior</label><input name="b_ant" type="radio" value="S" /></div>
			<div><label for="b_grade">Base na Grade</label><input name="b_grade" type="radio" value="S" /></div>
			<div><label for="b_grade">Base em Veículos Novos</label><input name="b_novos" type="radio" value="S" /></div>

not() selects all elements except the specified element.

prop() prop('checked', false) used to uncheck.

not(this).prop('checked', false); will uncheck all radios inputs except the selected one

  • 1

    I could give an example of when it would be necessary to have several elements radio representing the same field, but with different names?

  • @Andersoncarloswoss, is not the focus of the post evaluate one or another situation, I’m just answering a question. This you should ask the author of the post.

  • It’s just that as you suggested the solution, I thought you’d know, but thank you.

  • It is as I said in the reply - If it is necessary to keep the Names different - the use te such situation only the AP can explain. I understand you asked this question inappropriately with ulterior motives.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.