html form does not respond to hitting "enter" button - javascript

I have this html form, which does not actually sends data to a php file, buts sends data to a javascipt function.
Works fine if I hit the "Go" button, but if I choose something and hit "enter", does not work. Does not send the data to the function, that is.
I have made other forms with the same pattern, to send data to a javascript function in the same file and they work . This one refuses.
How do I fix this? Thanks
<form id="boroughform" enctype="multipart/form-data" method="post" action="#" onSubmit="return goborough(this); return false;" >
Choose borough:<br/>
<select name="boroughselect" id="boroughselect" >
<option selected value=" ">Choose...</option>
//fill the options with the results of a query performed eariler - works
<?php
for ($v=0; $v< sizeof($borough) ; $v++)
{echo '"<option value="'.$bid[$v].','.$bboxa[$v].','.$bboxb[$v].','.$bboxc[$v].','.$bboxd[$v].'" >'.$borough[$v].'</option>';}
?>
</select><br/>
<input type="submit" value="Go" name="postbor" class="formButton">
</form>
//the js
function goborough(g){
var binfo=g.elements['boroughselect'].value;
if(binfo!=" "){
//some cool openlayers staff here
return false;
}
else{alert('You have not chosen a borough !!! ');return false;}
}

In your form element (the select) try this,
onkeypress="if(event.keyCode==13) {this.submit();}"
Or use jquery,
$(document).ready(function() {
$("input").keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
$("#broughtform").submit();
}
});
});

Your problem is not in the code, but in that the select element has reserved the enter key for other purposes, see why doesn't hitting enter when a SELECT is focused submit the form?
Apply an onkeypress event to the select element to change this default behaviour.

If you're sure that everything is fine and it should go. Then you might use this:
onkeydown(submitform)
In the form tag, and in the function you should use this:
function submitform () {
if(event.keyCode == 13) {
// submit the form.. as enter key code is 13.
}
}
I am not sure why its not working. You should try to read and look at the console from the browser, it must tell you what is the error. Try doing that by pressing F12 in your Browser. You will get an error code there, try Googling it, or sharing it in the Question.

You should return true to submit the form but you are always returning false, return false and it prevents the submission.
JS:
function goborough(g){
var binfo=g.elements['boroughselect'].value;
if(binfo!=" "){
//some cool openlayers staff here
return true;
}
else{
alert('You have not chosen a borough !!! ');
return false;
}
}
HTML:
You have this
onSubmit="return goborough(this); return false;"
but, it should be
onSubmit="return goborough(this);"

Related

Partially update the current form if the target form has an error, else submit the target form

I have this idea for the script below:
What the script should do is that when the form id="try" is submitted by clicking the submit button, it would not be submitted immediately but rather check if there would be an error on the page where the form is to be submitted.
If there is an error, I can just display an error message by partially updating the div id="content" saying, "Sorry, your user action is currently not possible due to an unexpected issue."
If it has no error (the page "try1.php" was found and has no runtime errors on it), we submit the form and go to "try1.php", not that the contents of the "try1.php" would be sent into the div id="content"
HTML:
<div id="content">
THIS IS THE DIV: "content"
</div><br>
<form id="try" action= "try1.php" method="post">
<input type="submit" value="Try">
</form>
jQuery:
$(document).ready(function()
{
$("#try").submit(function(e)
{
e.preventDefault();
// get the action
var action = $(this).attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
I'm new to jQuery, do you have any advise on how can I do the if else statement? Is jQuery the right thing to use or are there other solution for this?
Thanks in advance.
Changing the form submit button to a regular button would help, as making this button call a function would do the trick, like:
<form id="try" action= "try1.php" method="post">
<input type="button" value="Try" id="submitButton"/>
</form>
Then in the JavaScript part:
$(document).ready(function()
{
$("#submitButton").click(function(e)
{
e.preventDefault();
// get the action
var action = $("#try").attr("action");
$("#content").load(action, function()
{
//if the action is loaded to the <div id="content"> without any errors:
document.getElementById("try").submit();
//else if the target page has an error:
$("#content").html("Sorry, your user action is currently not possible due to an unexpected issue");
});
})
});
Hope it solves the problem. For more clarifications, please comment.

How to change form url parameter on submit?

I have this form for processing..
<form action="driver.php" method="GET">
<input type="text" placeholder="Search" id="search" name="n">
<button type="submit">Submit</button>
</form>
by default the url is http://sites.com/driver.php?n=typedname
so i did modifications in .htaccess and convert it to http://sites.com/driver/typedname for SEO friendly urls modrewrite issue - 404 error thanks to anubhava
everything is well, but the problem now comes when I type and click the submit button, it will go to http://sites.com/driver.php?n=typedname
so how can I make it to go this url http://sites.com/driver/typedname instead after clicking submit?
I think javascript can do this, so i tagged it, hope im not wrong.
thanks.
jQuery
$('button[type=submit]').click(function(e){
e.preventDefault();
e.stopPropagation();
window.location = "http://sites.com/driver/" + $('#search').val();
return false;
});
or
$('form').submit(function(e) { // you really need to class/ID your form
// all that code
});
Now this is quick and dirty to give you the idea. You'd of course want to sanitize your input (good idea to do that on the front-end as well as the back-end).
You will have to handle form submit event yourself. Something like this:
document.querySelector('form').addEventListener('submit', function(e) {
e.preventDefault();
location.href = '/driver/' + this.elements.n.value;
}, false);

Bootstrap or jquery stopping form SUBMIT

Tired to make this parallax with bootstrap and jquery.. but FORM is not submitting while this code works fine separately if I run.. If someone can help me out in this..
Here is page : http://cellsouq.com/xtra/co/ (complete code)
Click on OPPORTUNITIES > FRANCHISE (on top navigation)
Click on APPLY ... it will scroll to FORM
Form is something like that with javascript
<script>
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
}
</script>
<form onSubmit="return funcFranchise(this)" class="form-horizontal" >
...
<input type="submit" value="Submit Request" class="btn bg-primary" >
</form>
If i remove Bootstrap it works fine. In whole code somewhere submit EVENT is blocked not sure... Please help me out..
You should return either true or false upon the completion your validations. So try like;
<script>
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
return true;
}
</script>
try this:
function funcFranchise() {
alert('Submitted Successfull');
// To validate form elements
$('.form-horizontal').submit();
}

Form dynamic attribute changing and submission not working

I have the following code:
Html:
<form action="/" id="mainForm" method="get">
<input type="text" name="val1" />
<button id="cmdSubmit">Submit</button>
</form>
<button id="cmdSubmit2">Submit 2</button>
Javascript:
$("#cmdSubmit2").bind('click', function () {
Submit2();
});
var Submit2 = function() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.submit();
}
What I'm trying to do is dynamically change the action attribute of a form with javascript and then submit it (to a different url).
What I expect to happen (in JsFiddle) is that clicking the submit button should load the jsfiddle home page, and clicking the Submit2 button should load a 404 page since the /testing url doesn't exist.
This works fine in chrome (28.0.1500.95), but does not work in Firefox (23.0.1) or IE for that matter(10.0.9200.16660).
None of these browser show any errors in the console either - I'm stumped. Any ideas?
JSFiddle
EDIT: I do actually have to clone the form, forgot to mention that. Also, this works fine in Safari (v5.1.7).
You need to somehow insert it in the DOM :
function Submit2() {
var form = $("#mainForm").clone();
form.attr("action", "/testing");
form.hide().appendTo('body');
form.submit();
}
fiddle
Works for me (FF 23.0)
You don't need to clone() the form. Try this:
var Submit2 = function() {
var form = $("#mainForm");
form.prop("action", "/testing");
form.submit();
}
Updated fiddle

How to prevent form from submitting multiple times from client side?

Sometimes when the response is slow, one might click the submit button multiple times.
How to prevent this from happening?
Use unobtrusive javascript to disable the submit event on the form after it has already been submitted. Here is an example using jQuery.
EDIT: Fixed issue with submitting a form without clicking the submit button. Thanks, ichiban.
$("body").on("submit", "form", function() {
$(this).submit(function() {
return false;
});
return true;
});
I tried vanstee's solution along with asp mvc 3 unobtrusive validation, and if client validation fails, code is still run, and form submit is disabled for good. I'm not able to resubmit after correcting fields. (see bjan's comment)
So I modified vanstee's script like this:
$("form").submit(function () {
if ($(this).valid()) {
$(this).submit(function () {
return false;
});
return true;
}
else {
return false;
}
});
Client side form submission control can be achieved quite elegantly by having the onsubmit handler hide the submit button and replace it with a loading animation. That way the user gets immediate visual feedback in the same spot where his action (the click) happened. At the same time you prevent the form from being submitted another time.
If you submit the form via XHR keep in mind that you also have to handle submission errors, for example a timeout. You would have to display the submit button again because the user needs to resubmit the form.
On another note, llimllib brings up a very valid point. All form validation must happen server side. This includes multiple submission checks. Never trust the client! This is not only a case if javascript is disabled. You must keep in mind that all client side code can be modified. It is somewhat difficult to imagine but the html/javascript talking to your server is not necessarily the html/javascript you have written.
As llimllib suggests, generate the form with an identifier that is unique for that form and put it in a hidden input field. Store that identifier. When receiving form data only process it when the identifier matches. (Also linking the identifier to the users session and match that, as well, for extra security.) After the data processing delete the identifier.
Of course, once in a while, you'd need to clean up the identifiers for which never any form data was submitted. But most probably your website already employs some sort of "garbage collection" mechanism.
Here's simple way to do that:
<form onsubmit="return checkBeforeSubmit()">
some input:<input type="text">
<input type="submit" value="submit" />
</form>
<script type="text/javascript">
var wasSubmitted = false;
function checkBeforeSubmit(){
if(!wasSubmitted) {
wasSubmitted = true;
return wasSubmitted;
}
return false;
}
</script>
<form onsubmit="if(submitted) return false; submitted = true; return true">
The most simple answer to this question as asked: "Sometimes when the response is slow, one might click the submit button multiple times. How to prevent this from happening?"
Just Disable the form submit button, like below code.
<form ... onsubmit="buttonName.disabled=true; return true;">
<input type="submit" name="buttonName" value="Submit">
</form>
It will disable the submit button, on first click for submitting. Also if you have some validation rules, then it will works fine. Hope it will help.
Create a unique identifier (for example, you can hash the current time), and make it a hidden input on the form. On the server side, check the unique identifier of each form submission; if you've already received that hash then you've got a repeat submission. The only way for the user to re-submit is to reload the form page.
edit: relying on javascript is not a good idea, so you all can keep upvoting those ideas but some users won't have it enabled. The correct answer is to not trust user input on the server side.
Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.
You could also display a progress bar or a spinner to indicate that the form is processing.
Using JQuery you can do:
$('input:submit').click( function() { this.disabled = true } );
&
$('input:submit').keypress( function(e) {
if (e.which == 13) {
this.disabled = true
}
}
);
I know you tagged your question with 'javascript' but here's a solution that do not depends on javascript at all:
It's a webapp pattern named PRG, and here's a good article that describes it
You can prevent multiple submit simply with :
var Workin = false;
$('form').submit(function()
{
if(Workin) return false;
Workin =true;
// codes here.
// Once you finish turn the Workin variable into false
// to enable the submit event again
Workin = false;
});
On the client side, you should disable the submit button once the form is submitted with javascript code like as the method provided by #vanstee and #chaos.
But there is a problem for network lag or javascript-disabled situation where you shouldn't rely on the JS to prevent this from happening.
So, on the server-side, you should check the repeated submission from the same clients and omit the repeated one which seems a false attempt from the user.
You can try safeform jquery plugin.
$('#example').safeform({
timeout: 5000, // disable form on 5 sec. after submit
submit: function(event) {
// put here validation and ajax stuff...
// no need to wait for timeout, re-enable the form ASAP
$(this).safeform('complete');
return false;
}
})
The simpliest and elegant solution for me:
function checkForm(form) // Submit button clicked
{
form.myButton.disabled = true;
form.myButton.value = "Please wait...";
return true;
}
<form method="POST" action="..." onsubmit="return checkForm(this);">
...
<input type="submit" name="myButton" value="Submit">
</form>
Link for more...
Use this code in your form.it will handle multiple clicks.
<script type="text/javascript">
$(document).ready(function() {
$("form").submit(function() {
$(this).submit(function() {
return false;
});
return true;
});
});
</script>
it will work for sure.
This allow submit every 2 seconds. In case of front validation.
$(document).ready(function() {
$('form[debounce]').submit(function(e) {
const submiting = !!$(this).data('submiting');
if(!submiting) {
$(this).data('submiting', true);
setTimeout(() => {
$(this).data('submiting', false);
}, 2000);
return true;
}
e.preventDefault();
return false;
});
})
the best way to prevent multiple from submission is this
just pass the button id in the method.
function DisableButton() {
document.getElementById("btnPostJob").disabled = true;
}
window.onbeforeunload = DisableButton;
To do this using javascript is bit easy. Following is the code which will give desired functionality :
$('#disable').on('click', function(){
$('#disable').attr("disabled", true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="disable">Disable Me!</button>
Most simple solutions is that disable the button on click, enable it after the operation completes. To check similar solution on jsfiddle :
[click here][1]
And you can find some other solution on this answer.
This works very fine for me. It submit the farm and make button disable and after 2 sec active the button.
<button id="submit" type="submit" onclick="submitLimit()">Yes</button>
function submitLimit() {
var btn = document.getElementById('submit')
setTimeout(function() {
btn.setAttribute('disabled', 'disabled');
}, 1);
setTimeout(function() {
btn.removeAttribute('disabled');
}, 2000);}
In ECMA6 Syntex
function submitLimit() {
submitBtn = document.getElementById('submit');
setTimeout(() => { submitBtn.setAttribute('disabled', 'disabled') }, 1);
setTimeout(() => { submitBtn.removeAttribute('disabled') }, 4000);}
Just to add to the possible answers without bypassing browser input validation
$( document ).ready(function() {
$('.btn-submit').on('click', function() {
if(this.form.checkValidity()) {
$(this).attr("disabled", "disabled");
$(this).val("Submitting...");
this.form.submit();
}
});
});
An alternative to what was proposed before is:
jQuery('form').submit(function(){
$(this).find(':submit').attr( 'disabled','disabled' );
//the rest of your code
});
<h3>Form</h3>
<form action='' id='theform' >
<div class='row'>
<div class="form-group col-md-4">
<label for="name">Name:</label>
<input type='text' name='name' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<label for="email">Email:</label>
<input type='text' name='email' class='form-control'/>
</div>
</div>
<div class='row'>
<div class="form-group col-md-4">
<input class='btn btn-primary pull-right' type="button" value="Submit" id='btnsubmit' />
</div>
</div>
</form>
<script>
$(function()
{
$('#btnsubmit').on('click',function()
{
$(this).val('Please wait ...')
.attr('disabled','disabled');
$('#theform').submit();
});
});
</script>
This is a clean Javascript code that prevents multiple valid submissions:
<script>
var form = document.querySelector('form');
form.onsubmit = function(e){
if(form.reportValidity())
// if form is valid, prevent future submissions by returning false.
form.onsubmit = (e)=> false;
return true;
}
</script>

Categories