Handlebars form submit does not work - javascript

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">
<i class="fa fa-times"></i>
<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();});

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
}

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();});

Related

Hidden Field Value in JavaScript is not posted

this error is (again) discussed a thousand times in different forums, but I don't find anything that would help me with my problem. I have a form, a hidden field and some links, that change the value of this field and submit the form. I checked it many times.
the function is called.
the ID is transferred to the function.
the hidden field can be accessed.
the value of the hidden field can be changed.
the called site has no value from the hidden field.
if I use a submit-button instead with an onclick="DeleteEvent(someValue)" the value is transferred over to the called site... so it IS the hidden field...
somehow... someone an idea what it could be?
Submit works, a href not...
Or could it be the problem of the div?
sourcecode:
function DeleteEvent(id){
var hiddenId = document.getElementById('hiddenIdField');
hiddenId.value = id;
document.forms['deleteForm'].submit();
}
<form action="" method="post" name="deleteForm">
<input type="hidden" id="hiddenIdField" name="hiddenField" value="testy" />
<div style="display: none" id="divText18">
<br />
<a href="" onclick="DeleteEvent(18)">
<img src="images/delete.jpg"/>
</a>
</div>
<!--
this is the working part:
<input type="submit" onclick="DeleteEvent(18)" />
-->
</form>
Your form not working because of active link event.
Use event.preventDefault() for onclick events.
To parse event in your function you need to send it to your function.
<form action="" method="post" name="deleteForm">
<input type="hidden" id="hiddenIdField" name="hiddenField" value="testy" />
<div style="display: none" id="divText18">
<br />
<a href="" onclick="DeleteEvent(18,event)">
<img src="images/delete.jpg"/>
</a>
</div>
<!--
this is the working part:
<input type="submit" onclick="DeleteEvent(18)" />
-->
</form>
function DeleteEvent(id,event){
event.preventDefault();
var hiddenId = document.getElementById('hiddenIdField');
hiddenId.value = id;
document.forms['deleteForm'].submit();
}
Prooblem in this code is link tag before image, it sends browser to nowhere on click before submit, so submit can't worki. Just give onclick event to image or give "javascript:;" as href to keep browser on page.
function DeleteEvent(id){
var hiddenId = document.getElementById('hiddenIdField');
hiddenId.value = id;
document.getElementById("deleteForm").submit();
}
<form action="" method="POST" id="deleteForm">
<input type="text" id="hiddenIdField" name="hiddenField" value="testy" />
</form>
<div style="display: inline" id="divText18">
<img src="images/delete.jpg" style="cursor: pointer;" onclick="DeleteEvent(18)" />
</div>
but if you have to use it with href, make it stay on page like
<a href="javascript:;" onclick="DeleteEvent(18)">
<img src="images/delete.jpg />
</a>

php Form with jquery validation issue

** Updated with additional code **
I am redesigning a site for someone and reusing some of the php code from the previous developer. The form submits and does validation server-side on the process page. This is obviously bad from a user experience perspective. I am trying to incorporate jquery validation. I am more of a designer and have limited knowledge on php and moderate jquery.
Its a pretty straight forward form that has 2 submit options at the end. 1 button for paying with a check, 1 for paypal.
The code being used for these buttons is completely bypassing my jquery form validation. If I put a simple submit button the jquery validation kicks.
This is the code for the 2 buttons being used.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$('form').validate();
});
</script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name: </label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a href="javascript:void(0)" onclick="document.regform.Submit.value = 'PayPal'; document.regform.submit()" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a href="javascript:void(0)" onclick="document.regform.submit()" class="btn btn-primary" >
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
The buttons are simply passing either paypal or null into the form submit process page and then redirecting after that. Is there a way I can make this pass jquery validation and then submit with those values?
You just need to add a rules object for the FirstName field and remove the attributes from the input element.
Also the following doesn't work:
// Uncaught TypeError: Cannot set property 'value' of undefined
document.regform.Submit.value = 'PayPal';
However if it did work there is a corner case, where the user clicks the paypal button but the form does not validate, the user then fixes the validation errors and submits the form with the check button. In this event the form will be submitted with Submit=PayPal.
jQuery(function($) {
var form = $('#lx'), submit = $('input[name=Submit]', form);
form.validate({
rules: {
FirstName: {
required: true,
minlength: 2
}
}
});
// lets keep JavaScript out of the DOM
$('#bypaypal, #bycheck').on('click', function(event) {
var paymentType = event.target.id === 'bypaypal' ? 'PayPal' : '';
submit.val(paymentType);
form.submit();
});
// this is just for demo purposes, you don't need it
form.on('submit', function() {
if (form.valid()) {
alert('Form is valid: Submit="' + submit.val() + '"');
}
});
});
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.jsdelivr.net/jquery.validation/1.13.1/jquery.validate.js"></script>
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname">
<span class="font-standout">*</span> First Name:
</label>
<div class="col-sm-8">
<input type="text" name="FirstName" class="form-control input-lg mrs mls" />
<input type="hidden" name="Submit" value="" />
</div>
</div>
<a href="javascript:void(0);" id="bypaypal" class="btn btn-primary">
<i class="fa fa-paypal"></i>
<br/>Pay with Paypal Online
</a>
<a href="javascript:void(0);" id="bycheck" class="btn btn-primary">
<i class="fa fa-check"></i>
<br/>Pay By Check
</a>
</form>
Probably what's going on is the inline-javascript is hi-jacking the code and it never makes it to the jQuery validation. So remove it. Also, it's a good idea to add IDs to the a tag submit buttons to easily capture the click event. You also need to suppress the default action of an a tag, so use event.preventDefault (note that you must pass the event param into the .click function)
(1) Remove inline javascript.
(2) Assign IDs to your anchor tags.
(3) Then, use jQuery to test for click event.
working jsFiddle
HTML:
<form id="lx" class="form-horizontal" action="reg_process.php" method="post" name="regform">
<div class="row mbs">
<label class="control-label col-sm-4" for="firstname"><span class="font-standout">*</span> First Name:</label>
<div class="col-sm-8">
<input type="text" id="firstname" name="FirstName" class="form-control input-lg mrs mls" min="2" required />
</div>
</div>
<a id="paypal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-paypal"></i><br/>
Pay with Paypal Online
</a>
<a id="normal_submit" href="javascript:void(0)" class="btn btn-primary">
<i class="fa fa-check"></i><br/>
Pay By Check
</a>
</form>
jQuery:
$('#paypal_submit, #normal_submit').click(function(e){
e.preventDefault; //stop a tag default action
var submit_type = this.id.split('_')[0]; //paypal or normal
var fn = $('#firstname').val();
if (fn=='' || fn.length < 4){
alert('Invalid first name');
$('#firstname').css({'background':'yellow','border':'1px solid orange'}).focus();
return false;
}else{
if (submit_type == 'paypal'){
$('#lx').val('PayPal').submit();
}else{
$('#lx').submit();
}
}
});
If you have multiple fields to check, here is another jsFiddle Demo that shows how to handle that:
http://jsfiddle.net/tyvk15cg/

JQueryMobile form always empty

I'm trying to do a simple JQM AJAX form post to a server - but for some reason, my form input values are always empty. (Even in the DOM inspector)
This is the 2nd page in my HTML - and the only form on the page. The console always prints out "[]"
<div data-role="page" id="login">
<div data-role="content">
<h2>
Login
</h2>
<form id="loginform" data-ajax="false">
<fieldset>
<input name="" id="userId" name="userId" placeholder="login" type="number">
<input name="" id="password" name="password" placeholder="password" type="password">
<input type="button" id="login_submit" data-theme="b" value="Submit">
</fieldset>
</form>
</div>
<script language="JavaScript" >
$(document).on('pagebeforeshow', "#login", function(){
$(document).on('click', '#login_submit', function() {
console.debug($('#loginform').serializeArray());
});
});
</script>
</div>
And the answer is obvious once it's posted into SO.
There's duplicate name attributes on the input fields - note the original issue was probably that the name attributes were set as "" - which would drop them from the form submission.
Try:
$(document).on('submit', '#loginform', function() {
console.debug($('#loginform').serializeArray());
});

call a method on form submit with list of arguments

I am catching event of form submit and adding divs to the DOM, code http://jsfiddle.net/testtracker/7rkX4/7/
now i want to pass some arguments to the function like name of the commenter, time comment was added etc. I want it to be something like this.
html
<form onsubmit="addComment('john deo','post_id')">
<input ......>
<input ......>
</form>
javascript
function addComment(commenter_name,post_id){
perform operation....
}
The code you posted works fine. The reason it would not work in jsfiddle is because your functions are declared in a document.ready type of block by default (see the onLoad in the drop down on the left?)
The proper way to bind event handlers would be to bind them in javascript. This would avoid the scope problem.
If you need to get an inline event handler working, you can explicitly define your function as global:
window.addComment = function (commenter_name,post_id){
perform operation....
};
You can store the name of the commenter in html for example.
Try this (see demo: http://jsfiddle.net/7rkX4/8/).
HTML
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Neha" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>
<div class="post">
<ul class="comments"></ul>
<div class="comment_entry">
<form method="post" action="#">
<input type="hidden" name="name" value="Danil" />
<input type="text" name="comment" placeholder="Leave comment" />
<input type="submit" value="submit" />
</form>
</div>
</div>​
JavaScript
$(document).ready(function () {
$('.comment_entry form').submit(function (e) {
e.preventDefault();
var name = $('input[name="name"]', this).val();
var comment = $('input[name="comment"]', this).val();
$(this).parent().prev().append('<li><a class="commenter_name" href="/">' + name + '</a><br />' + comment + '</li>');
});
});​
If I understand correctly you want to add some variable-value pairs to the form on submit. Why not add some input fields to your form with type="hidden", then you can modify their values in your javascript code as you like.

javascript post submit different from input submit click?

I have this code
<html>
<include jquery>
<script>
function crea()
{
var html = '<form method="get" id="popUpForm" name="popUpForm" action="form_ricorda_dati.php"><hr /><input type="hidden" name="mio" value="1" />input3<input type="text" name="input3" value="" /><br />input4<input type="text" name="input4" value="" /><br /><input type="submit" id="11" value="Procedi" /></form><br />submit';
var div = document.getElementById('cont');
div.innerHTML = html;
}
function prova()
{
$('#popUpForm').submit();
}
</script>
<body>
< a href="#" onClick="crea()">lancia funzione JS</a><br /><br />
<div id="cont"></div>
</body>
</html>
This code:
When I click on <a href="#" onClick="crea()"> it "shows" the form
into the <div id="cont">
Way 1: When I click on <a href=""
onClick="prova()">submit</a> it calls $('#popUpForm').submit();
Way 2: Click on <input type="submit" id="11" value="Procedi"
/>
Problem:
If I click <input type="submit" id="11" value="Procedi" /> I
reload the page and see correct query string (form action="get"). In
the reloaded page, if I "show" the form and click on the input I see the last
input (browser autofill okay).
If I click submit, after, I
don't see the query string. In the reloaded page if I "show" the form and
click on the input I don't see the last input (browser autofill fails).
(I see this problem in Chrome and IE, but not in Firefox.)
Goal
The browser autofill should always show.
The problem might be that the HTML form you are creating with JavaScript was not in the browser's DOM at the moment the page was loading. You can fix this by placing the form's HTML into your body tag to be rendered in the DOM, and hide it with JavaScript until a user clicks the crea link.
The problem number 2 seems to be that your link ( <a href="" onclick="prova()"... ) might go to the url given in the HREF attribute. Since that attribute is empty, your page goes to itself.
To make things easier, you should keep your HTML form out of your JavaScript logic. Also since you are using jQuery, I have converted your functions to binds.
Working example in JSFIddle.
<html>
<head>
<script type="text/javascript" src="url/to/jquery.js"></script>
<script type="text/javascript">
jQuery(function(){
var form = jQuery( '#form' ),
crea = jQuery( '#creaLink' ),
prova = jQuery( '#provaLink' );
form.hide();
crea.on( 'click', function(){
form.show();
});
prova.on( 'click', function(){
form.submit();
});
});
</script>
</head>
<body>
lancia funzione JS
<br />
<br />
<div id="form">
<form method="post" id="popUpForm" name="popUpForm">
<hr />
<input type="hidden" name="mio" value="1" />
input3
<input type="text" name="input3" value="" />
<br />
input4
<input type="text" name="input4" value="" />
<br />
<input type="submit" id="11" value="Procedi" />
</form>
<br />
submit
</div>
</body>
</html>​
It might not be a good idea to depend on browser's autofill as different browsers may have different behaviors. Now if I am correct in assuming that you want the values to be present in the fields even after the form data is received and processed at the server, then I would suggest you to make use of AJAX techniques. Send the form data in the background to the server and show only the result once you receive the response.

Categories