Sergi Sergi - 3 months ago 8
Javascript Question

Basic Javascript- HTML button

I'm trying to have a button that submits a text input, and have that input show as an alert. Here's my code so far (which shows an alert with "undefined"):

<p class="text-right"> <input id="input" type="text" placeholder= "Your Name"><button id="submit" type="submit"> Submit </button> </p>


And my Javascript code:

var input = document.getElementById("input").value;
var submit = document.getElementById("submit");


submit.addEventListener("click", function1);

var submit = document.getElementById("submit");

submit.addEventListener("click", function1);



function function1() {



alert(input.value);

}

Answer
var submit = document.getElementById("submit");
submit.addEventListener("click", function1);
function function1() {
    var input = document.getElementById("input").value;
    alert(input);
}

You're alerting input.value.value, but you already have the value in the input variable. EDIT :

var submit = document.getElementById("submit");
var input = document.getElementById("input");
submit.addEventListener("click", function1);
function function1() {
    alert(input.value);
}

Which is declaring the input once, and each time the function is called, you alert it's value.

Comments