0

Can someone help me understand why the console log fails to print the value if I wrap the input field in a form field?

HTML:

  <form>
      <input id="formEntry" type="text">
      <button id="btn-3">Add Custom Line</button>
  </form>

JavaScript:

 var addCustomLine = function(){
      var customLine = document.getElementById("formEntry").value;
      console.log(customLine);
 }

 document.getElementById("btn-3").addEventListener ("click", addCustomLine, false);
2
  • Works fine for me. Commented Mar 16, 2017 at 23:18
  • What do you mean by "fails if I wrap it in a form"? Are you saying the code works if you omit the <form> tags? Commented Mar 16, 2017 at 23:22

2 Answers 2

2

By not specifying the button type, it submits the parent form by default. You can prevent this behavior by setting the type explicitly to "button".

<button type="button" id="btn-3">Add Custom Line</button>
Sign up to request clarification or add additional context in comments.

Comments

0

A <button> in a <form> will submit that form by default, which will cause the page to reloaded and nullify all effects that the event handler had. You can however prevent that behaviour:

function addCustomLine(event) {
    event.preventDefault();
    …
}

You'll want to install that handler on the submit event of the form usually, not the click event of the button.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.