Steve Barron
Steve Barron

Reputation: 1

addEventListener for an element that is inside of a form

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

Answers (2)

AWolf
AWolf

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

Todd
Todd

Reputation: 5454

here's a demo

try this:

document.addEventListener("DOMContentLoaded", function(event) { 
  var btn = document.getElementById('addWord');
  btn.addEventListener('click', fillArray, false);

  function fillArray(e) {
    e.preventDefault();
    alert('foo');
  }
});

}

Upvotes: 1

Related Questions