Reputation: 1
I have a simple form where I want to input something and store it. The addEventListener() method will not work when the button is inside of the form. Here is the code, html first, then JavaScript
<!DOCTYPE html>
<html>
<head></head>
<body>
<form>
<h1>Enter words to display </h1>
<fieldset>
<input type="text" id="wordName" name="wordName">
</fieldset>
<button id="addWord">Add word</button>
</form>
<script type="text/javascript" src="ch2_ex2.js"></script>
</body>
</html>
Javascript:
var wordInput = document.getElementById("wordName");
var addWord = document.getElementById("addWord");
addWord.addEventListener("click", fillArray);
function fillArray() {
console.log("do something");
}
I find that the fillArray() method isnt being called. Why is this? I works when I put the button right below the <body>
, but not from within the <form>
Upvotes: 0
Views: 1343
Reputation: 8990
You could also change your button to the form submit button and prevent the default browser behavior. See my demo below.
var wordInput = document.getElementById("wordName");
var form_el = document.getElementById("myForm");
form_el.addEventListener("submit", function(evt) {
evt.preventDefault();
fillArray();
});
function fillArray() {
console.log("do something with "+ wordInput.value);
var out = document.getElementById("out");
out.innerHTML = "you've entered: " + wordInput.value;
}
<form id="myForm">
<h1>Enter words to display </h1>
<fieldset>
<input type="text" id="wordName" name="wordName"/>
</fieldset>
<input type="submit" value="Add word"/>
</form>
<div id="out"></div>
Upvotes: 0