Handlebars Form Submit Does Not Work
Solution 1:
Another possibility for running JS at the time of submit is to return false from the form element onsubmit attribute:
template.hbs
<form id="myForm" onsubmit="myFunc(); return false;">
<input id="textInput"type="text"></input>
<input type="submit"></input>
</form>
...
<script src="js/handleForm.js"type="text/javascript"></script>
handleForm.js
functionmyFunc() {
console.log("yo");
}
This will log "yo" in the browser console. It works because returning false in the onsubmit attribute prevents the browser's default action (which is an html thing, not a node or hbs thing). So, the page will not reload, and no query string will be added to the hyperlink, but myFunc() will run.
If you want to work with the form data, just get it from the DOM however you like. One option is to put an id on the text input (as I've done in template.hbs) and snag it with jQuery like so:
handleForm.js (revised)
functionmyFunc() {
var formText = $("#textInput").val();
// Do something with formText
}
Solution 2:
Perhaps handler is attached before Dom is compiled, try listening t body events, and filtering by selector, should listen to Dom nodes added in future too...
$(document.body).on("submit", "#messageForm", function() {alert();});
Post a Comment for "Handlebars Form Submit Does Not Work"