Why does it not work with the DOM Event Listener?
The call to addEventListener() is not closed.
document.getElementById("myBtn").addEventListener("click", functio_test;
To fix this, add a closing parenthesis:
document.getElementById("myBtn").addEventListener("click", functio_test);
// ^
See this working in the example below. Notice a few changes were made:
- function keyword added before function name:
function functio_test()
- event argument accepted:
function functio_test(e)
- event default behavior (button click submitting form) stopped:
e.preventDefault()
getting value from the form elements (instead of by id - since that only relates to the first input with that id attribute):
var x = document.forms[0].elements.type_test.value;
The <input> tags have no permitted content and thus are empty elements, so the closing slash was added to the end of the tags. For example:
<input type="radio" id="type_test" name="type_test" value="ola" />
// ^
The id attribute of the second radio button was changed because "The id global attribute defines a unique identifier (ID) which must be unique in the whole document."2
<input type="radio" id="type_test2" name="type_test" value="adeus" /> adeus <br>
Also if this code wasn't in the snippet sandbox, the <form> and <script> tags would be moved into a <body> tag under the <html> tag, since those are flow content and the only permitted contents for <head> are: "One <head> element, followed by one <body> element."1
Also the id attribute of the form has the text 'form` prepended because "Using characters except ASCII letters and digits, '_', '-' and '.' may cause compatibility problems, as they weren't allowed in HTML 4. Though this restriction has been lifted in HTML 5, an ID should start with a letter for compatibility."3
document.getElementById("myBtn").addEventListener("click", functio_test);
function functio_test(e) {
e.preventDefault();
var x = document.forms[0].elements.type_test.value;
if (x == "ola") {
alert("Ola José");
} else if (x == "adeus") {
alert("Adeus José");
} else
alert("Continua José");
}
<form id="form0" name="form_test" action="test_form.php" method="post">
<input type="radio" id="type_test" name="type_test" value="ola" /> ola <br>
<input type="radio" id="type_test2" name="type_test" value="adeus" /> adeus <br>
<input type="submit" value="submit" /> //imput only use for POST method
<button id="myBtn">Try it</button>
</form>
1https://developer.mozilla.org/en-US/docs/Web/HTML/Element/html)
2https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
3https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id)
document.getElementById("myBtn").addEventListener("click", functio_test;