2
I am making a form that if the user leaves the name field blank, display the message in the field instead of an alert. The document.write
does not work with function through an event. I am using innerHTML
and textContent
. However I can not display the message. I made two codes, let’s see:
<html>
<body>
<script>
function validar() {
if (document.formulario.nome.value.length == 0) {
var alerta = "O nome deve ser informado";
var aviso.innerHTML = alerta;
}
}
</script>
<form name="formulario">
Nome: <input type="text" name="nome">
<input type="submit" value="Enviar" name="cadastro" onclick="validar()">
</form>
</body>
</html>
Second code:
<html>
<body>
<script>
function validar() {
if (document.formulario.nome.value.length == 0) {
var alerta = document.getElementById('alerta');
alerta.textContent = "O nome deve ser informado";
}
}
</script>
<form name="formulario">
Nome: <input type="text" name="nome"> <input type="submit"
value="Enviar" name="cadastro" onclick="validar()">
</form>
</body>
</html>
In your first example you are making a
innetHTML
in a variableaviso
. Where you use this variable?– Pedro Camara Junior
@Pedro Camara Junior I use the variable in <span id=warning></span> I am doing so, without quotation marks, because I saw an example of a code to show the time on the page where I used <span> to display an innerHTML footprint information block
– André Nascimento
You need to use the
getElementById
, so you’re not making any reference tospan
. Take a look at the answer I posted.– Pedro Camara Junior
@Pedro Camara Junior why you wear the symbol of '$'?
– André Nascimento
Is only one good practice, to differentiate variables from other elements. It will work the same way without the dollar.
– Pedro Camara Junior
@Pedro Camara Junior I ran your code on the response itself and it worked. I copied it, pasted it into my IDE, but it didn’t work. I changed some things and it didn’t work. Follow jsfidle: http://jsfiddle.net/hkoe6zm0/2/
– André Nascimento