问题
I have a form that within a handlebars put the submit does not work, I have to do? Can anyone help?
<script id="chat-window-template" type="text/x-handlebars-template">
<a href="#" class="close"><i class="fa fa-times"></i></a>
<a href="#">
<span class="pull-left">
<img src="{{ user_image }}" width="40">
</span>
<span class="contact-name">{{user}}</span>
</a>
<div class="panel-body" id="chat-bill">
<form id="messageForm">
<input id="nameInput" type="hidden" class="input-medium" value="Macbook" />
<input id="messageInput" type="text" class="form-control" placeholder="Digite uma mensagem..." />
<input type="submit" value="Send" />
</form>
</div>
</script>
$("#messageForm").submit( function() {alert();});
回答1:
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();});
回答2:
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
function myFunc() {
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)
function myFunc() {
var formText = $("#textInput").val();
// Do something with formText
}
来源:https://stackoverflow.com/questions/37840611/handlebars-form-submit-does-not-work