简体   繁体   中英

Check if at least one RADIO BUTTON has been checked

I'm creating a dynamic form, there may be X fields to fill, for example there may be 10 inputs texts, 5 selects, 3 Radio etc.

I created the entire structure to assemble this form dynamically and it is working as expected.

However my biggest problem is when I will check if at least one RADIO BUTTON has been checked. If it were in a static way the solution would be simpler, as it could simply take the ID of the main DIV and see if one is checked

<div id="$id">
 <?php for($i = $inicio; $i <= $fim; $i++){ ?>
   <label>
    <input  
     id="<?= $id ?>"    
     name="<?= $name ?>"
     value="<?= $i ?>" 
     type="radio"
   />
   <span><?= $i ?></span>
  </label>                                                 
<?php } ?>
</div>

You don't need to pay much attention to the details of the code, because I gave a summary, just to explain that it is built dynamically

I needed to find some way of submitting the form to go through it all and check which are RADIOS from that individually enter each one and check if at least one is checked, if not add a message saying that the field is mandatory and I do this with the other RADIOS until passing through all.

Does anyone have any suggestions on what to do or some material that I can read?

Do you try it with required? I think that for the front you don't need anything else

<label>
    <input type="radio" name="gender" value="male" required>
    Male
</label><br>
function checarRespostas() {

  var perguntas = $('[id^=pergunta]');
  perguntas.each((index, pergunta) => {
    var respostasChecadas = $(pergunta).children('label').children('input[type=radio]:checked');

    if (respostasChecadas.length == 0) {
      alert(`Responda a ${pergunta.id}`);
    }

  });

}
<p>Pergunta 1</p>
<div id="pergunta_1">
    <label>
        <input type="radio" name="resposta_1" value="Opcao1"> Opção 1
        <br>
        <input type="radio" name="resposta_1" value="Opcao2"> Opção 2
    </label>
</div>

<p>Pergunta 2</p>
<div id="pergunta_2">
    <label>
        <input type="radio" name="resposta_2" value="Opcao1"> Opção 1
        <br>
        <input type="radio" name="resposta_2" value="Opcao2"> Opção 2
    </label>
</div>
<br>

<button onclick="checarRespostas()">Enviar</button>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM