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!
Related
I have a HTML form with some fields and a submit button. couple of fields are mandatory. I have a set of JavaScript code which i need to execute only if the form validation is successful. If there is some validation error on the form, the JavaScript code shall not execute. Below is the sample code:
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
/*JavaScript*/
$("#sampleForm").submit(function(){
//Set of JavaScript code to execute if validation is success.
});
For me above JavaScript code does not work.
Please help!
In a comment you've said:
But if i use $("#sampleForm").submit() to submit the form, the form gets submitted but if i write function inside submit() ($("#sampleForm").submit(function(){ //Set of JavaScript code to execute if validation is success. });) then nothing happens !
That function is called when the submit event is fired, but the event isn't fire when the controls are invalid because the form won't be submitted.
The individual form controls get an invalid event when the user tries to submit the form when they're invalid. You can use that to provide feedback beyond what the browser supplies if you like:
$("#sampleform")
.on("submit", function() {
alert("Got the 'submit' event; form is being submitted");
})
.find("input, select")
.on("invalid", function() {
// Will fire for *EACH* invalid control
alert("Validation failed");;
});
Fiddle (Stack Snippets don't allow form submission even when it's cancelled.)
In case you need to submit the form programmatically (by calling submit), you can use checkValidity first to see if the form is valid:
// When submitting programmatically
var form = $("#sampleForm");
if (form[0].checkValidity()) {
form.submit();
}
Side note: When you use jQuery to submit the form (above), submit event handlers will be called. But if you use the DOM to submit the form ($("#sampleForm)[0].submit()), they won't be.
Just write a submit handler and execute your codes.
$("#sampleForm").submit(function(){
// Your code.
})
Submit handler triggers only when you complete the validation by HTML5 custom validator.
Here is a demo : http://jsfiddle.net/sureshatta/9ky8Z/118/
Html5 form have checkValidity method.Also since it is a form and button type is submit it will default throw an error pop up if it is not valid. checkValidity method return a boolean value true if it is valid. You can take a look in this method for further your job
$("#sampleForm").submit(function(e) {
var result = document.getElementById('firstname').checkValidity()
console.log(result) // will log true
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sampleForm" method="post" action="">
<input type="text" id="firstname" required />
<input type="text" id="secondname" required />
<input type="submit" value="Submit" />
</form>
Thanks everyone for the answers!
I tried each one of your's solution which helped me to reach to my solution. Below worked for me:
if($("#sampleForm").valid()){
$("#sampleForm").submit();
//Set of JavaScript code to execute.
}
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()"/>
In PHP program, I have JS function which validates submit <form ...onsubmit='return isOK();'>. It works OK. The problem is I want it to work only for particular submits, not for all. Is there any way inside the JS function to find out which submit was pressed, or some PHP trick
instead of onsubmit u can use onClick.
<input type="submit" onclick="return pressSubmit1()" value="submit1" />
<input type="submit" onclick="return pressSubmit2()" value="submit2" />
<form action="action.php" method="post">
...
<input name="submit" type="button" value="check me" onclick="submitform('check')" />
<input name="submit" type="button" value="do not check me" onclick="submitform('not check')"/>
</form>
in javascript:
function submitform(check)
{
if(check=='check') checkfrom();
}
in PHP
if($_POST['submit']=="check me")
checkform();
<form class="allowed" onsubmit='return isOK();'>
----
function isOK() {
if($(this).hasClass('allowed')) {
// Do stuff
}
}
your question is not clear, are you using a single submit button or different ones. If you're using different submit buttons then ofcourse you can make checks based on the id of the submit button. On the other hand if is a single submit button then it depends on what the conditions are for submitting or not submitting
It's better you write some HTML and Java Script code which you are using. So, it's easy to correct mistake is you have made somewhere in code snippet.
We can check which submit button is clicked, using PHP.
In the PHP page corresponding to the form submit, write
if(extract($_POST) && isset($submitbtn1)) {
// some validation for first submit button
}
elseif(extract($_POST) && isset($submitbtn2)) {
// some validation for second submit button
}
Note: we can use $ followed by submit button name inside the extract function. ie. $submitbtn1 is same as $_POST['submitbtn1']
Yes different onclick looks fine as mentioned in the accepted answer. But in the event handler you should have the
code as below. Note the preventDefault.
Also since submit is A button that submits the form. You can use button type instead of submit type and then there is no need for preventDefault. Here is the link of the code http://jsbin.com/wikose/4/
function testlogin(){
event.preventDefault();
var test = 'not validated';
if(test === "validated")
alert("not valid login");
else
$('form').submit();
return false;
}
<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.
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.