Reputation: 21
I am relatively new to JavaScript. Right now I'm having my HTML call a JS function when it is submitted, and have the JavaScript function validate the form. However, the form seems to submit regardless of what the JS function returns. Can anyone help me with this?
<html>
<body>
<p>Can you see this?</p>
<form action="actions.js" method="POST" onsubmit="validate()">
<input type="radio" id="yes" name="yes" value="yes">
<label for="yes">Yes</label><br>
<input type="radio" id="no" name="no" value="no">
<label for="no">No</label><br>
<input type="submit" value="Submit" />
</form>
<script type="text/javaScript">
validate() {
var yes = document.getElementById("yes").value
if (yes === "yes") {
return true
}
else {
return false
}
}
</script>
</body>
</html>
Upvotes: 0
Views: 758
Reputation: 163
I would recommend having your js in a separate folder-file structure and have your html file link to it using the <script type="text/javascript" src="./YOURFOLDER/index.js"></script>
Then in the index.js file you can place your code
validate(e) { //pass in the event as clicking the button causes an event to be triggered
var yes = document.getElementById("yes").value
if (yes == "yes") {
return true
}
else {
e.preventDefault() // js function to prevent default behavior of submit
return false
}
}
https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
helpful resources https://developer.mozilla.org/en-US/docs/Learn https://www.w3schools.com/js/default.asp
Upvotes: -1
Reputation: 1041
You need to prevent the form submitting when validation fails.
This is done using event.preventDefault()
Your check for which radio is selected also doesn't quite work correctly, I've made a basic amend below, but this will need updating when you add more radios.
document.querySelector("#form").addEventListener("submit", function(event) {
var yes = document.getElementById("yes").checked
if (yes == true) {
return true
}
else {
event.preventDefault();
return false
}
});
<p>Can you see this?</p>
<form method="POST" id="form">
<input type="radio" id="yes" name="yes" value="yes">
<label for="yes">Yes</label><br>
<input type="radio" id="no" name="yes" value="no">
<label for="no">No (won't submit)</label><br>
<input type="submit" value="Submit" />
</form>
Upvotes: 2
Reputation: 781068
You have to return what the validation function returns.
<form action="actions.js" method="POST" onsubmit="return validate()">
Upvotes: 2