I have a form box and I want it to accept the value that the user types and write it to a list below. I don't want to use functions, it's a challenge.
I have the following code:
<!DOCTYPE html>
<html lang="es">
<head>
<meta charset="UTF-8">
<title>Mi documento</title>
<script>
var valorname = document.f1.nombre.value
</script>
</head>
<body>
<form name="f1">
<input type="text" name="nombre" onchange="document.getElementById('elemento1').innerHTML=valorname">
</form>
<br><br>
<ul>
<li id="elemento1"></li>
</ul>
</body>
</html>
As you can see I have painted a form box and a list. As I said, what I want is that when typing in the text box, as it changes, when leaving it, the list element is filled with the value entered in the box.
The problem I have is that I get undefined
, as if I didn't save what was entered in the text box in the variable. I don't know if it's a runtime problem, although I think the JavaScript code is capable of getting the data and storing it in the variable; I say this mainly because doing it with a function does work.
As I say, I don't want to use functions. It is simply a challenge.
Thank you very much. All the best.
The problem is that you retrieve the value of the input on page load, when it hasn't even been created.
You must retrieve the value when the change event occurs:
In the onchange it is better for you to bring the value directly to the object, not to the variable that you have declared in your script, in this way:
Since the valuename variable, being in the head , is being loaded when the content of the body has not yet reached the DOM, that is why the reference remains as undefined .
If you also want to store the value in a variable, you can declare the variable at the beginning of the script and leave the onchange event like this:
Thus, when launching the onchange event, you get the value of said input and store it in the valuename variable .
Okay. Thank you both very much. Both possibilities are valid. The only catch is that I'm not storing the value in any variables, so you won't be able to reuse it.