0

function controllaFormStanza(){
    var stanza = document.myForm.stanza.value;

    var ok = true;
  
        if (stanza.length == 0){
            document.getElementById("noNomeStanza").innerHTML="Dai un nome alla tua stanza!";
            ok = ok && false;
        }
        else {
            document.getElementById("noNomeStanza").innerHTML="";
            ok = ok && true;
        }
        for(i=0;i< document.myForm.immagine.length; i++) {
            if(document.myForm.immagine[i].checked) {
                ok = true;
            }
            else {
                document.getElementById("noImmagine").innerHTML="Seleziona una icona per la tua stanza!";
                ok = false;
            }
        }
  
        if (ok){
            document.myForm.submit();
            return true;
        }
        else {
            return false;
        }
            
    }
  
    <form action="formStanza.php" method="post" name="myForm" enctype="multipart/form-data">
    <div class="row">
                <table>
                   <tr>
                      <td align="center">Nome nuova stanza:
                   <tr>
                      <div <?php if (isset($name_error)): ?> <?php endif ?> >
                      <td><input type="text" name="stanza" placeholder="Inserisci nome stanza" size="30" maxlength="40"/>
                   <tr>
                      <td align="center">
                         <div class="avvertenza" id="noNomeStanza">  </div>
                         
                         <div class="row">
            <table>
               <tr>
                  <td align="center">Icona della stanza:
               <tr>
                  <td>
                  <input type="radio" name="immagine" class="sr-only" id="bagno" value="bath.png">
                     <label for="bagno">
                        <img src="icone/icone_stanze/bath.png" alt="bagno">
                     </label>
                  
                  <input type="radio" name="immagine" class="sr-only" id="cameretta" value="bedroom.png">
                     <label for="cameretta">
                        <img src="icone/icone_stanze/bedroom.png" alt="cameretta">
                     </label>
               <tr>
                  <td align="center">
                     <div  class="avvertenza" id="noImmagine">  </div>
            </table>

         </div>
         
                 <div class="row">
            <table>
               <tr>
                  <td align="center">
                
                     <input type="submit" name="mySubmit" class="bottone btn btn-lg btn-info" value="Crea stanza" onclick="return controllaFormStanza()">
            </table>

         </div>


      </form>

I have a form in a php file. When submitting this form, I call a control js function. The controllaFormStanza() function verifies that the "stanza" field of type text is not empty and that a value has been selected in the radio. In this second part I have a problem. Even if a value is selected in the radio, I still get the error message that should appear when nothing is selected. Why? Where am I wrong? This is my function:

function controllaFormStanza(){
    var stanza = document.myForm.stanza.value;


    
    var ok = true;
  
        if (stanza.length == 0){
            document.getElementById("noNomeStanza").innerHTML="Dai un nome alla tua stanza!";
            ok = ok && false;
        }
        else {
            document.getElementById("noNomeStanza").innerHTML="";
            ok = ok && true;
        }
        for(i=0;i< document.myForm.immagine.length; i++) {
            if(document.myForm.immagine[i].checked) {
                ok = true;
            }
            else {
                document.getElementById("noImmagine").innerHTML="Seleziona una icona per la tua stanza!";
                ok = false;
            }
        }
  
        if (ok){
            document.myForm.submit();
            return true;
        }
        else {
            return false;
        }
            
    }
5
  • Please show a minimal reproducible example that contains both js and html. Commented Aug 26, 2021 at 15:51
  • I have insert the reproducible example @t.niese Commented Aug 26, 2021 at 15:57
  • You should never set the variable to true after initialization. Only set to false when something fails. Your code says: Is this radio button selected? No? okay it is an error..... You are not seeing if any of them are checked. Commented Aug 26, 2021 at 16:12
  • How can I change? I can't get to the solution @epascarello Commented Aug 26, 2021 at 16:26
  • your ok logic is highly flawed. ok = ok && false; is the same thing as ok = false;. Also most of your ok statements are not even in a loop so they are useless. They will just be over-written by the next if/then statement. Commented Aug 26, 2021 at 16:55

2 Answers 2

1

Your loop is forgetting the previous value when you're doing ok = true; or ok = false;. I bet that if you select the last element of the radios the function validates the form.

you have the solution in your code, by using the && operator like you did when checking the text field

Since you are setting error messages within the loop, I suggest you using another variable and place the error handling outside of the loop.

let AnyRadioButtonsChecked = true;
for(i=0;i< document.myForm.immagine.length; i++) {
    if(document.myForm.immagine[i].checked) {
        //                     vv--------------------- check this
        AnyRadioButtonsChecked &&= true; // equivalent to AnyRadioButtonsChecked = AnyRadioButtonsChecked && true;
    }
    else {
        //                     vv--------------------- check this
        AnyRadioButtonsChecked &&= false;
    }
}
if (!AnyRadioButtonsChecked) {
    document.getElementById("noImmagine").innerHTML="Seleziona una icona per la tua stanza!";
}
ok &&= AnyRadioButtonsChecked;

It could be simplified using Array.prototype.some() that will return true if any element match the condition :

let AnyRadioButtonsChecked = document.myForm.immagine.some(element => element.checked);
Sign up to request clarification or add additional context in comments.

3 Comments

I always have the same problem even doing it this way. I don't understand where I'm wrong
document.getElementById("noImmagine").innerHTML="Seleziona una icona per la tua stanza!"; should be outside of the loop
To get out of the for loop when I encounter the checked value I put a "break" in the if. But nothing changes, in the end the variable ok is always equal to false. Because? I do not understand
0

I would just simplify the code and check each thing.

Easiest thing is to look to see if a checkbox is selected, not to loop over each one.

function controllaFormStanza() {

  const form = document.myForm;
  const isStanzaValid = form.stanza.value.trim().length > 0;
  document.getElementById("noNomeStanza").innerHTML = isStanzaValid ? '' : "ERROR";

  const isImmagineValid = form.querySelector('[name="immagine"]:checked') !== null;
  document.getElementById("noImmagine").innerHTML = isImmagineValid ? '' : 'ERROR';

  return isStanzaValid && isImmagineValid;
}
<form action="formStanza.php" method="post" name="myForm" enctype="multipart/form-data">
  <div class="row">
    <table>
      <tr>
        <td align="center">Nome nuova stanza:
          <tr>
            <div <?php if (isset($name_error)): ?>
              <?php endif ?>
              <td><input type="text" name="stanza" placeholder="Inserisci nome stanza" size="30" maxlength="40" />
                <tr>
                  <td align="center">
                    <div class="avvertenza" id="noNomeStanza"> </div>

                    <div class="row">
                      <table>
                        <tr>
                          <td align="center">Icona della stanza:
                            <tr>
                              <td>
                                <input type="radio" name="immagine" class="sr-only" id="bagno" value="bath.png">
                                <label for="bagno">
                        <img src="icone/icone_stanze/bath.png" alt="bagno">
                     </label>

                                <input type="radio" name="immagine" class="sr-only" id="cameretta" value="bedroom.png">
                                <label for="cameretta">
                        <img src="icone/icone_stanze/bedroom.png" alt="cameretta">
                     </label>
                                <tr>
                                  <td align="center">
                                    <div class="avvertenza" id="noImmagine"> </div>
                      </table>

                    </div>

                    <div class="row">
                      <table>
                        <tr>
                          <td align="center">

                            <input type="submit" name="mySubmit" class="bottone btn btn-lg btn-info" value="Crea stanza" onclick="return controllaFormStanza()">
                      </table>

                    </div>


</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.