Reputation: 168
I'm simply trying to get the value of an input box embedded in a form tag.
For example, this works just fine.
<div>
<label>First Name</label>
<input id="firstName" type="text" required />
</div>
<button type="submit" onclick="getName()">Submit</button>
<script type="text/javascript">
function getName() {
var name = document.getElementById('fistName').value;
console.log(name);
}
</script>
This outputs whatever value is enter in the console when the submit button is clicked. However if I put it in a form like below it doesn't return anything.
<form>
<div>
<label>First Name</label>
<input id="firstName" type="text" required />
</div>
<button type="submit" onclick="getName()">Submit</button>
</form>
Does the form tag add some protection? How can I get the value out of an input tag inside a form?
Upvotes: 0
Views: 83
Reputation: 11
Button of type submit refreshes the page. Also the console gets cleared. So it does output but gets immediately cleared. Try changing the button type to "button". Then it will not refresh the page and you will see the output.
Upvotes: 0
Reputation: 218828
it doesn't return anything
Yes it does.
However, since you're submitting a form, the page is also immediately refreshing and you're starting over from scratch.
The form isn't "protecting" anything. The code is doing exactly the same thing in both cases. But in the second case the form
is also doing something else (loading the page) before you've physically had time to see the result.
Upvotes: 4