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;
}
}
oklogic is highly flawed.ok = ok && false;is the same thing asok = 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.