I want to validate my code with javaScript and determine if it is okay to submit to php.
If it is correct I want the form to not submit to the php file that I have in 'action'.
If it is inncorrect I do not want the form to submit to the php file, and I want to display an error message.
Right now the form uses "onsubmit="return Validate()"" to call the validation function which displays a message and returns false to stop the form action. The problem is that the form action does not get stopped, and still runs. For some reason when I click the submit button twice the php message gets displayed then the java script message gets displayed.
My html form:
<form action="<?= base_Url(); ?>index.php/Login/loginuser" onsubmit="return Validate();" method="post" name="Login" accept-charset= "utf-8" >
Username: <input type="text" name="Username" maxlength="21" />
<br><br>
Password: <input type="text" name ="password" maxlength="20" />
<br><br>
<input type = "submit" value = "Login" class = "loginbutton" />
</form>
My java script function.
function Validate() {
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
From what I read online when onsubmit="return Validate()" gets returned false the form is supposed to not run. Thought this was right but cant figure out why its not working.
EDIT: I am useing codeigniter to display the url, and for other purposes on the project.
EDIT2: This is still not working... When the onsubmit is changed too, onsubmit="false" the php will not be called. Which is expected. When changed to onsubmit="true", the php will be called. Which is expected.
When onsubmit="return Validate();" and the Validation() function on says "return false;". It will for as expected. Same with return true. But when code gets placed in the function the boolean does not appear to be returned. The code below will not stop the php file from running when the login name is empty.
function Validate() {
if (document.getElementsByName("Username")=="" )
{
document.getElementById("errorMSG").innerHTML = "Validate ran...";
return false;
}
else
{
return true;
}
}
I am testing with chrome and firefox. There are no error messages displayed in the console on google chrome. I am not familiar with the debug tool for fire fox but i see no error messages displayed either.
I am now going to change the jquery script line to an updated version, maybe it will help..
I am using code igniter with controllers, views, libraries...
Everything was working fine until i started with the javascript validation.
You should use return false only when mandatory fields are empty
function Validate() {
// check whether mandatory fileds have some value or not
// document.getElementsByName("Username") always returns an array and will be robust way to access value by index 0 iin array like - document.getElementsByName("Username")[0]
if(document.getElementsByName("Username")[0].value == "" || document.getElementsByName("password")[0].value)
{
document.getElementById("errorMSG").innerHTML = "All fields required";
return false;
}
return true;
}
Please try this one 100% work
onsubmit="myFunction();return false;"
1.It should be just "Validate()" for onsubmit, not "return Validate().
And use onclick instead of onsubmit
Try this
<input type = "submit" value = "Login" class = "loginbutton" onclick = "Validate()"/>
Related
Here's my situation. I have a submit button. When clicked, some backend/database validation takes place and if everything's good, submit the form and disable the button so the form can't be submitted twice. If it does not pass validation, submittal cannot take place and the button stays active, so the user can resubmit the form. It sounds simple but I can't make it work. This is a C# web application.
I have tried to add the code to the button on page load. When the submit button is clicked and if validation fails, remove the code that disables the button. But here is my problem. Since the "disable" code is removed and the user fixes any error and resubmit, the button can be clicked more than one as the code is no longer there.
I do not want to use Ajax for this because the backend check is very complicated. Is there another way to do it? I've tried to add the "disable" code on "load" but it does not work on post back when the validation fails.
if (window.addEventListener)
window.addEventListener("load", lockSubmit, false);
else if (window.attachEvent)
window.attachEvent("onload", lockSubmit);
else window.onload = lockSubmit;
Any help is appreciated.
Try the snippet below
window.onload = function(){
// Insert the following function somewhere in your .js file / section
(function prevent_over_submitting(){
var form = document.forms.theform;
if(form || form.nodeName == 'FORM'){
form.onsubmit = function(){
form.submit.value = 'Proccesing...';
form.submit.disabled = true;
};
}
})();
};
While your form should look something like this one
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<input type="text" name="lastname" value="" />
<input type="submit" name="submit" value="submit" />
</form>
Here is a working jsBin so you can play around.
Update:
The logic behind the snippet above
// server-side code (rather in pseudo-code this time)
if(form_has_been_submitted){ // check if the form has been submitted
errors[] = validate_data(post_data); // call the method to validate data
if(errors_array_is_empty){ // if everything is fine
submit_data(); // submit data
redirect_or_do_something; // (maybe) do other things
} // otherwise don't do anything
}
// validation method
validate_data(post){ // the only argument here represents all your form data
error = array;
if(post['firstname'] == wrong){ // check for error
error['firstname'] = 'Check your firsname'; // if you found one, push it to the error array
}
if(post['lastname'] == wrong){ // the same as in previous case
error['lastname'] = 'Check your lastname'; // the same as in previous case
}
return error; // return that array, it might be full or empty
}
// client-side code
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>MyApplication</title>
<script type="text/javascript">
// the JavaScript snippet from above
</script>
</head>
<body>
<form id="theform" method="post" action="">
<input type="text" name="firsname" value="" />
<!-- show the error if you found one, otherwise show an empty string -->
<span><% (error['firstname'] ? error['firstname'] : "") %></span>
<input type="text" name="lastname" value="" />
<!-- same as in the previous case -->
<span><% (error['lastname'] ? error['lastname'] : "") %></span>
<input type="submit" name="submit" value="submit" />
</form>
</body>
</html>
As you can see, the JavaScript snippet above only disables the submit button onclick to prevent over-submitting; it will be enabled once the page is loaded again. This isn't my favorite way of validation but I followed your logic.
you can add this code in the onclick function:
First, add a global javascript variable, say var click = false;
and add this condition before validation occurs:
if(click){
return false
} else {
your normal validation code
}
if your page reloads each time you submit, then there is no need to add anything further, but if doesn't then add setInterval method which will reset the click variable for next use if validation fails.
The state of the click variable will remain true after first click and will further stop multiple clicks, unless page reloads or we reset the variable manually through code.
My form currently has two submit buttons. One for Search and the other for a Mark Complete function. I need to show a confirm dialog box ONLY when the "Mark Complete" button is clicked to submit the form with that validation is passed. Is it possible to identify this? I currently have the below confirmComplete function:
function confirmComplete() {
alert("confirmComplete");
var answer=confirm("Are you sure you want to continue");
if (answer==true)
{
return true;
}
else
{
return false;
}
}
Any help would be appreciated!
Set the onclick attribute of the "Mark Complete" button to this
onclick="return confirm('Are you sure you want to continue')"
and remove the confirmComplete function from the form
You can. You can put your buttons like this
<input type="submit" value="Search" />
<input type="submit" value="Mark Complete" onclick="{return confirmComplete();}" />
When Mark Complete button is clicked then the confirmComplete function will be called and when user says OK in the confirm dialog then only the form will be submitted.
You need to do the event from the click on the button and not the form submission. There is no crossbrowser way to know what submitted the form.
So here is a bypass solution:
<form id="frm" action="page.php" method="post" onsubmit="return onSubmit();">
<input />
<input type="submit" value="sub1" onclick="sub1();" />
<input type="submit" value="sub2" onclick="sub1();" />
</form>
<script type="text/javascript">
<!--
var frm = document.getElementById('frm');
function onSubmit(){
return false;
}
function sub1(){
alert('s1');
frm.submit();
}
function sub2(){
alert('s2');
}
//-->
</script>
when you call "confirm()" javascript pop up function , like onclick="return confirm('Are you sure to proceed?')" ,confirm box get appear with message 'Are you sure to proceed?' with two options 'ok' and 'cancel'.when you click ok it return true and proceed further execution of web page or if you click cancel it will return false and stop further execution of web page.
I don't know for an input tag, but it didn't worked for me with the click event directly on a button. In my case, the form was posted right away.
Here's a possible solution for a form with many buttons (for which only one of them must display the confirmation message)
In the view:
<FORM name="F_DESTINATION_DB" id="F_DESTINATION_DB" method="POST" onsubmit="return popConfirmationBox('<?php echo LanguageControler::getGeneralTranslation("DELETE_CONFIRMATION_MESSAGE", "Deleting is an irreversible action. Are you sure that you want to proceed to the deleting?");?> ','DELETE_DB_BUTTON')">
Javascript (in external file for code reuse):
/**
* Display a confirmation message box to validate if we must post the page or not.
*
* #param message String to display
* #param tagId String id of the tag that must display the message.
*
* #return Boolean (confirmation)
*/
function popConfirmationBox(message, tagId){
var confirmation = true;
if (typeof tagId === 'string' && document.activeElement.id.toUpperCase() === tagId.toUpperCase()) {
if (typeof message === 'string' && message.length > 0) {
confirmation = window.confirm(message);
}
}
return confirmation;
}
I had quite a hard time to achieve this (needed lot of research and testing), but the resulting code is pretty simple.
By default, I assume that the confirmation is yes (in case the clicked button is not the one meant to display the message or if the user doesn't supply a valid message string).
Additional note: Of course, this code won't do the trick if the user browser block client side code.
I hope it will help someone,
Jonathan Parent-Lévesque from Montreal
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.
I am developing a web application in which I have created a form and in the onSubmit event of the form I have called a java script function which will check for "Field must not left blank" condition if it is left blank the form must not be posted so I have written following code:
Jsp Page Form
<form action="Result.jsp" name="validityCheck" onsubmit="return fnCheckEmptyField();">
<input type="text" name="txtIIDN" id="txtIIDN" style="font-size:medium;" onkeypress="return fnKeyPress(event)"/>
<input type="submit" id="btnValidityCheck" value="Check Validity" />
</form>
Javascript code is as follows
<script>
function fnCheckEmptyField()
{
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == null)
{
document.getElementById("lblValidityStatus").innerHTML="";
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
return false;
}
else
{
return true;
}
}
</script>
When I try to submit the form the javascript function gets executed and then form will gets posted whether the return value is true or false.
I dont want to submit the form when the return value is false i.e when field is empty
and also the condition in onsubmit event onsubmit="return fnCheckEmptyField(); showing me an error
Cannot return from outside a function or method.
Can you figure out what is the mistake I am commiting and possible solution for that?
Remove the onsubmit event on the form and In the submit button HTML, put this
<input type="submit" id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();" />
Adding on to what Furqan said, you should probably use the button and an onclick event to check the form, and if the form is valid, then call .submit() on your form.
I tend to not even use a submit button, I just have a normal button, and have it run javascript... then the javascript submits the form.
Example (HTML submit button):
<button id="btnValidityCheck" value="Check Validity" onclick="return fnCheckEmptyField();">Click Here</button>
Javascript function:
function fnCheckEmptyField() {
var strDomain= document.getElementsByName("txtIIDN").value;
if(strDomain == "") {
document.getElementById("lblValidityStatus").innerHTML="Domain Name Field Can't be Left Blank";
}
else {
document.getElementById("myFormId").submit();
}
}
Notice that if the javascript feel that the form is valid, THEN it will submit your form. You need to define an id for your form tag for this to work.
Also, I changed the == null check to == ""... that may have been causing issues...
Cheers!
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/