When trying to give a value to <input>
it from a function, it makes me a trick but it does not keep the value. I mean, for a hundredth of a second you see it put the value but it disappears.
Do you know why?
Thank you very much to all.
<form action="" name="formulario" id="formulario">
<input type="text" id="texto1" name="texto1" value="" placeholder="nombre">
<input type="text" id="texto2" value="" placeholder="apellido">
<input type="text" id="texto3" value="" placeholder="edad">
<button id="boton1">Enviar</button>
<button id="boton2">Eliminar</button>
</form>
<script>
function datos() {
var uno = document.getElementById("texto1").value;
var dos = document.getElementById("texto2").value;
var tres = document.getElementById("texto3").value;
var arreglo = [uno, dos, tres];
return arreglo;
}
function borrar() {
document.getElementById("texto1").value = "rrrrr";
document.getElementById("texto2").value = "rrrrr";
document.getElementById("texto3").value = "rrrrr";
}
function alerta() {
var arreglo = datos();
alert(`Su nombre es ${arreglo[0]}, su apellido ${arreglo[1]} y su edad ${arreglo[2]}`);
}
boton1.onclick = alerta;
boton2.onclick = borrar;
</script>
The first problem is that when placing a button inside a form, by default it will send said form when clicked as if a:
To avoid that behavior you can add a:
that way the form will not be submitted when the button is clicked.
Second, if you want the delete button to leave the form fields blank you don't need to create a function, just add:
and the code looks like this:
I hope it is what you are looking for, greetings.