How not to allow recording if dynamically created radios are not marked

Asked

Viewed 43 times

0

I am trying to do a validation so that only be allowed to record the records if all radios are marked, or to Sim or to Não, I’m creating the radios dynamically but the code I did to try this validation is not working, as can be seen below.

The button that triggers the action is like this:

<button type="submit" class="btn btn-primary" id="Finaliza">
    Gravar
</button>

The script I made:

document.getElementById("Finaliza").onclick = function() {
    var radios = document.getElementsByName("Status[]");
    for (var i = 0; i < radios.length; i++) {
        if (radios[i].unchecked) {
            alert("Você precisa selecionar o status");
        }
    }
};

The creation of radios are like this:

<p>
 <label class="radio-inline">
    <input type="radio" name="Status[]<?php echo $IdItemCheckList; ?>" value="1"> Sim
 </label>
 <label class="radio-inline">
    <input type="radio" name="Status[]<?php echo $IdItemCheckList; ?>" value="0"> Não
 </label>
</p>
  • I think the reason is getElementsByName. You are using .getElementsByName("Status[]"), as long as the inputs are named after Status[]<?php echo $IdItemCheckList; ?>, that is to say, Status[]Qualquercoisa is different from Status[].

1 answer

1


The problem is the getElementsByName("Status[]") since none of the inputs will have the name Status[], assuming that the <?php echo $IdItemCheckList; ?> does not return empty. Simply create a new attribute/class and use it instead of getElementsByName.


However, an easier solution... If both have the same name (and in this case it is the same $IdItemCheckList), just add the required, this will cause the browser to prevent submit.

<form>
  <div>
   <label class="radio-inline">
      <input type="radio" name="Status[]A" value="1" required> Sim
   </label>
   <label class="radio-inline">
      <input type="radio" name="Status[]A" value="0" required> Não
   </label>
  </div>
  <div>
   <label class="radio-inline">
      <input type="radio" name="Status[]B" value="1" required> Sim
   </label>
   <label class="radio-inline">
      <input type="radio" name="Status[]B" value="0" required> Não
   </label>
  </div>
  <button type="submit" class="btn btn-primary" id="Finaliza">
      Gravar
  </button>   
</form>

Browser other questions tagged

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