I wrote simple custom validation on javascript based on this doc. I want it to display an alert if a select has been chosen on "Si" and the text fields are left blank. I don't get why it isn't displaying the message.
<html>
<head>
<link rel="stylesheet" type="text/css" media="screen" href="mistylesheet.css"/>
<script type ='text/javascript'>
function mivalidate (elem1, elem2, elem3, elem4) {
if(elem1.value=="Si")&&(elem2.value.length==0)&&( (elem3.value.length==0)||(elem4.value.length==0)){
alert("Por favor, especifique un nombre y un email o teléfono de contacto en su recomendación ");
elem1.focus();
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<form onsubmit='return mivalidate(document.getElementById("recomiendaONo"),document.getElementById("nombreRecomendado"), document.getElementById("emailRecomendado"),
document.getElementById("telefonoRecomendado"))'>
<ta开发者_开发技巧ble class="layouttable">
<tr class='row1'><td> <b>¿Recomendaría nuestros servicios a otra empresa o persona? </b></td></tr>
<tr class='row2'><td>
<select id = "recomiendaONo" name="recomiendaONo" class="required">
<option value="">Seleccione su respuesta</option>
<option value="Si">Sí</option>
<option value="No">No</option>
</select>
</td></tr>
</table>
<div class='margenrecomendaciones'>
<table>
<tbody>
<tr>
<td><div align="left">Nombre:</div></td>
<td><div align="left"><input class="texto" id="nombreRecomendado" name="nombreRecomendado" type="text" size="30"/></div></td>
</tr>
<td><div align="left">Email:</div></td>
<td><div align="left"> <input class="texto" id="emailRecomendado" name="emailRecomendado" type="text" size="30"/></div></td>
</tr>
<tr>
<td><div align="left">Teléfono:</div></td>
<td><div align="left"> <input class=" texto" name="telefonoRecomendado" id="telefonoRecomendado" type="text" size="30"/></div></td>
</tr>
</tbody>
</table>
</div>
<input type="submit"/>
</form>
</body>
</html>
You need to wrap your entire if
statement in parentheses.
This:
if (elem1.value == "Si") && (elem2.value.length == 0) && ((elem3.value.length == 0) || (elem4.value.length == 0))
should be:
if ((elem1.value == "Si") && (elem2.value.length == 0) && ((elem3.value.length == 0) || elem4.value.length == 0)))
(I also added spaces around the operators and after the if
to make everything more clear and readable, and you should as well. Also, using a text editor or IDE that shows matching braces really helps keep track of them.)
You need to enclose whole if
condition into braces:
if (...) {
alert(...);
}
And I always suggest to use firebug or similar tool in such cases: it will show you all javascript errors in a very clear way.
精彩评论