How can I prevent a webform from submiting on 'Enter' - javascript

I have a type ahead text field, and when the user hits "Enter" I want to make an ajax call and not submit the form at the same time. My html looks like this:
<input id="drug_name" class="drugs_field" type="text" size="30" onkeypress="handleKeyPress(event,this.form); return false;" name="drug[name]" autocomplete="off"/>
<div id="drug_name_auto_complete" class="auto_complete" style="display: none;"/>
<script type="text/javascript">
//<![CDATA[
var drug_name_auto_completer = new Ajax.Autocompleter('drug_name', 'drug_name_auto_complete', '/sfc/pharmacy/auto_complete_for_drug_name', {})
//]]>
</script>

You should add an event handler to the form itself which calls a function to decide what to do.
<form onsubmit="return someFunction();">
And then make sure that your someFunction() returns false on success. If it returns true the form will submit normally (which is what you are trying to prevent!). So you can do your AJAX call, see if it succeeded, and return false.
Doing it this way you can provide a fallback in case your AJAX call fails and submit the form normally by returning true from your function.

Trap the event and cancel it.
It's something like trap onSubmit(event) and event.ignoreDefault(). The event can tell you that it was triggered by a keystroke, and which.

You could use a regular button that submits the form on click instead of your submit button.
If you want the enter key to work in other fields, just handle it there and submit the form.

in the input element for the button do:
<input type='submit' value='submit' onclick='submiFunction(); return false;'>
or on the form itself
<form blabla onsubmit='someAjaxCall(); return false;'>
Which should stop the form from submitting.
the return false is the action that actually stops the form from submitting (it cancels the current event, which is sbumit)

Related

How should I use a window.confirm dialog box with a form?

I have tried window.confirm on a submit button saying "Are you sure" but even if I click on no it submits itself? Is this the wrong way of using it?
<button type="submit" class="btn btn-primary" onclick="window.confirm('Are you sure you want to transfer to user?')">
Transfer
</button>
use this
<form onsubmit="return confirm('Are you sure you want to transfer to user?')">
</form>
confirm returns a boolean. To make it work you will need to add return in the front:
return confirm(...);
http://jsfiddle.net/fu5LuLmx/
Instead of attaching to the click event, you might also want to consider attaching it to the submit event of the form, such that this piece of code would execute whenever the form is being submitted, not only when clicking this button.
You have to prevent from submitting so remove the onclick event, and add a onsubmit event on the form
<form name="form" id="myForm" onsubmit="return ask();">
<script>
function ask() {
if (window.confirm('Are you sure you want to transfer to user?')) {
return true;
} else {
return false;
}
}
</script>

Triggering onclick event of Input/Form

<form method="POST" onsubmit="return false;">
...
<input type="submit" name="button" value="Login" onclick="require('file.js').submitForm(this.form);">
...
</form>
How can i trigger onclick event of this INPUT element (so it can submit the form) in Internet Explorer 9 using javascript?
I tried:
document.getElementsByName("button")[0].click()
and
document.getElementsByName("button")[0].onclick()
but neither works.
(document.getElementsByName("button").length = 1)
you can use
document.getElementsByTagName("form").submit();
and for click event you can use this
element = document.getElementsByName("button")[0]
if (typeof element.onclick == "function") {
element.onclick.apply(element);
}
Looking beyond the surface of your question, I believe you're trying to trigger a form post AND handle the submission with some client-side logic.
The code you have prevents the form from being posted because of "return false;". When the button is clicked, it'll triggered the submit event, which is blocked. So how do you know that the button is triggered or not, knowing the results are the same?
For simpler coding logic, put the JavaScript call either in the form tag or the button but not both. My advice is to leave the button be. type="submit" means it will submit the form. The the form itself has a JavaScript function that decides whether to post or not.
<form method="POST" onsubmit="return prepost();">
...
<input type="submit" value="Submit">
</form>
<script>
function prepost(){
// if the form needs to be stopped
return false;
// if the form needs to be posted
return true;
}
</script>
Answer: The form didn't submit if I left some fields blank. When i put correct values in right fields it submitted correctly using above click() method. Thank you all for answers.

Form Not Validating when Using Anchor to Submit

I'm trying to submit a form using an anchor tag. However, the validation function doesn't seem to get triggered. I've since replaced the anchor with a submit button and it now works. Still, I'm curious why the previous anchor link didn't work.
The code is
function validate() {
/* validation code here */
return status;
}
<form id="myForm" action="/response_page.php" onsubmit="return validate();" method="POST">
<!-- form elements here -->
Submit
</form>
With this code, clicking the link goes straight to *response_page.php*. But when replaced with a submit button
<input type="submit" value="submit" />
WITHOUT changing the validate function and form tag, the validate function is called correctly. What's wrong with the anchor?
Thanks
This is expected behavior.
From the MDN on the submit function :
The form's onsubmit event handler (for example, onsubmit="return
false;") will not be triggered when invoking this method from
Gecko-based applications. In general, it is not guaranteed to be
invoked by HTML user agents.
If you want to validate your code in your link, just call the validate function explicitely :
<a id=subbut href="#" class="submit_button">Submit</a>
...
document.getElementById('subbut').addEventListener('click', function(){
if (validate()) document.getElementById('myForm').submit();
});

Form fields value get reset without page load

Following is my code in which i am trying to accomplish, when user clicks on the submit button then my javascript function sets all the value to null in the textfields of the form whose id='contact_form' without loading the page . Kindly let me know how can i modify the following code to accomplish the functionality i've been trying to do.
Thanks!!
<script type='text/javascript'>
$(document).ready(function(){
$('#love').click(function(e) {
document.contact_form.name.value = '';
alert('aloha!!');
//stop the form from being submitted (not working fine)
e.preventDefault();
}
}
</script>
<form name='abc' action='' id='abc' >
<input type="submit" id='love' />
</form>
I have also tried the following function it worked fine but its not preventing from the page load
<script type='text/javascript'>
function js(){
document.contact_form.name.value = '';
//stop the form from being submitted (NOT WORKING!!)
preventDefault();
}
}
</script>
If you try onsubmit="return false;" in the form tag your form will not be submitted. Unfortunately it will NEVER be submit. Unless you are not planning to submit it via AJAX you have to modify your onsubmit event like this:
<form onsubmit="return callFunction()">
function callFunction() {
if(condition)
return true;
else
return false;
}
$("#abc").submit( function() {
// do everything you want.
return false; //will prevent the reload.
});
To have a function execute when the form submits you have to do something like this;
<form onsubmit="return validate();">
your form here
</form>
Then you can have your check in a function called 'validate()' (or whatever you want to call it)
Make sure the validate() function returns true is the form is allowed to submit, or returns false if the page is not allowed to submit.
Also put id's and names on your input elements, that way you can access them much easier.
Assuming you have an HTML like this :
<form>
<input type="text" id="text" />
<input type="submit" id='submit' value="clear above field without reloading" />
</form>
And you want the text field value to clear when a user submits without reloading using jQuery, then following script will be your remedy :
$(function(){
$('#submit').click(function(){
$('#text').value('');
})
});
A form can be submitted in many ways, not only by clicking on a submit buttons. You should really watch for submit events, and cancel them with preventDefault (instead of click events that might trigger the submit). See #user1359163's answer.
But you problem seem to be document.contact_form.name.value. There is no property contact_form on the document object, so this will raise an error. The preventDefault is not executed, your form gets submitted and you never see the error. Set your debugger to "Stop on errors"!
You might want something like document.forms["contact"], but I don't know your HTML. An id selector for the input element would be the better choice.

Passing parameters from JavaScript

I have the typical HTML "contact me" page, i.e. name, e-mail address and message. Since I want to do input validation on the page itself using JavaScript, I can't use a submit button, otherwise, the attached JavaScript function would be ignored. At least that's how I understand it, CMIIW.
I tried to load the next page writing location = mail.php but it appears that the form parameters don't get passed to my PHP page this way.
How do I validate input in JavaScript and pass parameters to my PHP page when ok?
TIA
Steven
You can use a form with an onsubmit handler on it, that returns false if the validation failed. If the check is ok, return true and the form will submit normally.
You'd have a javascript function something like this:
function check_it_all() {
if (all_ok) {
return true;
} else {
return false;
}
}
And the form
<form action=..... onsubmit="return check_it_all();">
....
</form>
Use the onSubmit event. Attach it to your form and if it returns true then your form will be sent to the PHP page. Read more here.
You should still use the submit button to submit the form, that is the correct behavior.
Input validation should be done using the <FORM>'s onSubmit event.
It should look something like this:
<script>
function validate() {
var isFormValid = whatever; // validate form
return isFormValid;
}
</script>
<form action="your.php" method="POST" onSubmit="return validate()">
<!---fields--->
</form>
The function validate() returns a bool.
This will stop the submission if validate() returns false.
<input type="submit" onclick="return validate()" value="click" />
I am an aspx.net developer so I am used to putting the validation call on the button.
If possible can't you use a JavaScript library like Jquery? It probably would make your life alot easier and they have tons of plug-ins for validation.
Such as
http://bassistance.de/jquery-plugins/jquery-plugin-validation/

Categories