javascript vs jQuery form validation - javascript

Hi I have a simple form validation before I submit the form.
the validation if working fine with simple javascript function but I try to use the jQuery but its not working with as expected.
Here is the code I am using:
JSP:
<form action="/newManager.do" onsubmit="return validateListPropFields()" method="post">
<input type="hidden" name="operation" value="saveNewPropManagerInfo"/>
<td>Name<span class="required">*required</span></td>
<td><input type="text" name="name" id="name" placeholder="John Doe" /></td>
<input type="image" src="../images/common/submit_property.png" alt="Submit"/>
</form>
Javascript works fine:
function validateListPropFields(){
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
}
JQuery doesnot works:
function validateListPropFields(){
jQuery.noConflict();
(function($) {
$(function() {
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
});
})(jQuery);
}
Here I want to understand what makes the jQuery to not to work as expected?

In case of jQuery your validateListPropFields() function does not return anything. In this function there is an anonymous function which returns true or false but that has no effect on the outer function.
Though I have no Idea why would you want to complicate things so much I made some adjustments to your code so that it would work:
function validateListPropFields(){
jQuery.noConflict();
return (function($) {
return (function() {
var name = jQuery("#name").val();
if( name==""){
return false;
}
else{
return true;
}
});
})()(jQuery);
}
By submiting this code I am not saying that this is a good way to do this. I just wanted to illustrate how to make those inner anonymous functions work for your outer function.

You must import the jquery library first
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>

It works for me
function validateListPropFields() {
if ($("#name").val() == "") {
return false;
} else {
return true;
}
}

Related

How to delay on checkform using javascript?

I tried to delay for 10 sec before submit form like this but not work. It's will be still return true by not to delay.
<form class="form" method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" >
<input type="submit" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
var test = "1";
setTimeout(function(){
if(test != '0'){
return false;
}
else
{
return true;
}
}, 10000);
}
</script>
I want to know, how to delay on checkform using javascript ?
You must return to the checkForm function. A return inside a callback does not return to the outer function. Even if it did it must be immediate, not 10 seconds later
You could use a flag so you can call the function again inside the delay by submitting the form again
var allowSubmit = false;
function checkform(form) {
if (allowSubmit) {
return true;
} else {
var test = "1";
setTimeout(function() {
if (test === '1') {
// when validation passes resubmit with updated flag
allowSubmit = true;
form.submit();
}
}, 10000);
return false;
}
}
Here is a better way to do it if you have jQuery library included. In your case, the page gets submitted to itself and gets refreshed, so your 10 seconds get reset.
<form class="form" method="post" action="" enctype = "multipart/form-data" >
<input type="submit" name="submit" value="OK">
</form>
$(function(){
$("form").bind("submit", function(e){
e.preventDefault();
e.stopPropagation();
var test = "1";
setTimeout(function(){
if(test != '0'){
//return false;
alert("false");
}else{
alert("true")
//return true;
}
}, 10000);
});
});
So the problem here is that a submit request is has the same outcome as if you were to return something in a function.
For example if you had something like this:
function returnExplanation(){
return 0;
console.log("You will never see me");
}
You will never see the text in the console after the return.
A submit functions the same. although there are a few other ways to make this happen, I made a few adjustments to your code to achieve what you were looking for.
<form class="form" id="submitForm" method="post" action="" ENCTYPE = "multipart/form-data">
<input type="button" name="submit" value="OK">
</form>
<script language="JavaScript" type="text/javascript">
$(document).ready(function () {
$('#submitForm').on('click', function ()
{
var test = 1;
setTimeout(
function ()
{
if (test !== 0)
{
console.log("false");
return false;
} else
{
console.log("true");
return true;
}
}, 10000);
$('#submitForm').submit();
});
});
</script>
The first thing I did was give your form an "id". this allows jQuery (or javascript) to easily decipher exactly which element they should be communicating with.
Next, I removed your "onsubmit" attribute and added the appropriate jQuery to respond to the click event.
After that, I changed your button from a "submit" to a "button" type.
lastly, after the timeout, your form still submits with the line that reads:
$('#submitForm').submit();
I hope this helps you on your way to becoming a better HTML / jQuery programmer.

Two JavaScript functions onsubmit and onclick

I have two JavaScript functions to check two fields (input title and textarea)
form name="myform" onsubmit="return Checkthis()"
button type="submit" onclick="Checkthis();return false;"
Inside Checkthis() I call Check1() and Check2() and in onsumbit=/onclick=. I call only on Checkthis()
However, only the first function is checked onsubmit and onclick; I have tried to remove Checkthis() and call two functions like onClick="Check1();Check2();" but this doesn't work either.
function Check1() {
var msg_area = document.getElementById("mydiv1");
if () {
return false;
}
}
function Check2() {
var msg_areaa = document.getElementById("mydiv2");
if () {
return false;
}
}
function Checkthis() {
Check1();
Check2();
}
I have tried with: onsubmit ="Checkthis()" and onsubmit="return (Check1() && Check2());"
Any method I use only the first function is checked!
Okay this might not be a popular answer, so downvote away, but it will probably work.
Use jQuery:
$(document).ready(function(){
$("#wtvrDiv").click(function(){
Check1();
Check2();
});
});
To better explain my comments, give this a shot.
HTML:
<form name="myform">
<input type="text" id="titleID" />
<input type="text" id="textareaID" />
<button type="button" onclick="checkthis()">Submit</button>
</form>
Javascript:
var check1 = function () {...} // Don't submit, just see if it's valid
var check2 = function () {...} // Don't submit, just see if it's valid
var checkthis = function() {
if (check1 && check2) {
document.getElementById("myform").submit();
}
}
This page is also very helpful for getting started with form validation.

javascript return value Part 2

Had some great help yesterday, and have a followup question/problem. Regarding an HTML form, when the user clicks onSubmit="return outer()", the function 'outer' only returns one of the two functions inside (either checkname or checkpostal). How do I get it to check both functions? Noob question I'm sure, but I want to understand, and not just copy paste from the plethora of forms out there.
var postalconfig = /^\D{1}\d{1}\D{1}\-?\d{1}\D{1}\d{1}$/;
function outer() {
function checkname(f_name) {
if (document.myform.f_name.value == "") {
alert("Enter your First Name");
return false;
} else {
alert("valid First Name");
return true;
}
}
return checkname();
function checkpostal(postal_code) {
if (postalconfig.test(document.myform.postal_code.value)) {
alert("VALID postal");
return true;
} else {
alert("INVALID postal");
return false;
}
}
return checkpostal();
} //end of outer
The HTML:
<form name="myform" action="index.php" onSubmit="return outer();" method="post">
First Name
<input name="f_name" type="text" />
<br />
Telephone
<input name="telephone" type="text" />
<br />
<input name="Submit" type="submit" value="Submit Form" >
</form>
the execution of the function outer() stops whenever your return.
try this single return statement:
return checkname() && checkpostal();
When you write return checkname();, your function stops immediately.
There is no way to return a value and then run the rest of the function.
Instead, you need to call both inner functions, then use logical operators to combine them into a single boolean.
For example:
return checkname() && checkpostal();
Just do something instead or the returns or at the end do.
return checkName() && checkPostal();
What you're doing is technically valid, though may I advise that you define the functions separately. Use outer simply to call them and check their values, so you'd have:
function outer(){
return (checkname() && checkpostal());
}
function checkname(){
// Code for checkname
}
function checkpostal(){
// Code for checkpostal
}

Check if multiple functions are true, then do something

I am stuck on what I thought was a simple PEBCAK error on my part. I am trying to verify all of my functions are true before I submit a form, but cannot figure for the life of me what is wrong. Below is my javascript code:
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
function checkname())
{
if(name condition)
{
return true;
}
else {
return false;
}
}
function passwordcheck(){
if(password condition)
{
return true;
}
else {
return false;
}
}
html below:
<form id="newaccount" name="newaccount" method="post" onSubmit="accountcode.php">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New" onClick="return checknewaccount()"/>
</form>
When i click "New, nothing happens, and I know the accountcode.php is not running, because nothing happens on the database end and there are no errors reported.
To sum up, my question is how checknewaccount() does not work? Does it have something to do with how I am calling them?
I am new to javascript so if I am completely off on my implementation, I apologize. Thank you very much for the help!
you've got the form syntax wrong - onsubmit = the name of the js function to call, action = the url...
<form action="accountcode.php" id="newaccount" name="newaccount" method="post" onSubmit="return checknewaccount()">
<input type="text" id="email" onBlur="emailvalid()"/>
<input type="text" id="username" onBlur="checkname()" />
<input type="password" id="password" onkeyup="passwordcheck()"/>
<input type="submit" value="New"/>
</form>
Fully tested code:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
The form in the above code will only submit if the textbox has a value of test
A slightly better implementation would be:
<html>
<head>
<script type="text/javascript">
function checknewaccount() {
if(emailvalid() && checkname() && passwordcheck()) {
return true;
} else {
document.getElementById('validation').innerHTML = 'Validation failed!';
return false;
}
}
function emailvalid() {
var emailAddress = document.getElementById('email').value;
return (emailAddress=='test');
}
function checkname() {
return true;
}
function passwordcheck() {
return true;
}
</script>
</head>
<body>
<div id="validation"></div>
<form action="#" onsubmit="return checknewaccount();">
<input type="text" id="email" name="email"/>
<input type="submit"/>
</form>
</body>
</html>
As this at least tells the user the form wasn't submitted. Even better would be to give the user a more detailed reason why but that's beyond the scope of this question...
This part's fine (I took the liberty of fixing the indentation):
function checknewaccount(){
if(emailvalid()&& checkname() && passwordcheck())
{
return true;
}
else{
return false;
}
}
Although you could improve it:
function checknewaccount(){
return emailvalid() && checkname() && passwordcheck();
}
This part is a syntax error (to put it mildly):
function emailvalid(), checkname(), passwordcheck(){
if(condition){
return true;}
else{return false;}
If that's not a real quote from your code, you'll have to update your question (though I may not be here by then to update this answer). Not much point in asking about code and then quoting pseudo-code in the question. (At the very least, the pseudo-code is missing the final }.)
The same sort of thing is true for your functions in the form:
function emailvalid()
{
if(email condition)
{
return true;
}
else {
return false;
}
}
That's fine (assuming that email condition is still psuedocode), but there's no need for the if:
function emailvalid()
{
return email condition;
}
In terms of "nothing happens," make sure you have debugging tools you can use. Chrome has Dev Tools built in, just press Ctrl+Shift+I. For Firefox, you can install the excellent Firebug. Recent versions of IE have dev tools built into them as well (for older versions you can download a free version of Visual Studio that can plug into the browser). Any of these will tell you about syntax and other errors, let you walk through your code statement-by-statement, etc., which is crucial to figuring out what's happening.
Here's a quickly dashed-off version of what I think you're trying to do. I wouldn't do it this way, but I've made the minimal changes to make it work:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<input type="text" id="email" name='q' onblur="emailvalid()">
<input type="text" id="username" onblur="checkname()" >
<input type="password" id="password" onkeyup="passwordcheck()">
<input type="submit" value="New">
</form>
Notes on that:
As Basiclife pointed out, your form code has issues. Those are fixed above.
Above I've used action="http://www.google.com/search" but of course for you it would be action="accountcode.php" (or at least, I think it would).
Use onsubmit for the form submission handler, not onclick on the submit button. You can't cancel a form submission reliably cross-brower via the submit button's onclick.
In onsubmit, make sure you use return — e.g., onsubmit="return checknewaccount()", not onsubmit="checknewaccount()" — because we want to make sure the event stuff sees the return value. We don't care if the event stuff doesn't see the return value of our other checks (onblur="emailvalid()"), but if we did, we'd need returns there as well.
Only one of the fields above has a name attribute; none of yours do. Only fields with name attributes get submitted with forms. I've only used one name for my example because I only want to submit one field to Google, but for your purposes, you're going to want name attributes on all three fields. This brief article has a discussion of id vs. name and what they're for. You sometimes want both.
I've put the attributes in all lower-case, which is best practice (and required if you want to use XHTML).
However, I've removed the / from the ends of the inputs. This is a bit off-topic, but at the apparent level you're working at, you don't want to try to use XHTML, use HTML. Using XHTML correctly is technically difficult, both in authoring and server configuration, and even then you have to serve it as tag soup to IE or it won't handle it properly. XHTML has its place, but in the vast majority of cases, there's no reason to use it.
With the above combined with the JavaScript below, there's no purpose whatsoever to the handlers on the individual fields. I've left them, though, because I assume you're doing more than just the checks below — there's an example further down showing those handlers doing something useful.
JavaScript:
function checknewaccount() {
return emailvalid() && checkname() && passwordcheck();
}
function emailvalid() {
var element;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
return element.value.indexOf('#') > 0;
}
function checkname() {
var element;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
function passwordcheck() {
var element;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
return element.value.length > 0;
}
Live copy
Things change slightly if the emailvalid, et. al., functions are going to do something to let the user know the fields are invalid, such as highlighting their labels:
HTML:
<form action="http://www.google.com/search"
method="GET" target="_blank"
onsubmit="return checknewaccount()">
<label>Email:
<input type="text" id="email" name='q' onblur="emailvalid()"></label>
<br><label>Username:
<input type="text" id="username" onblur="checkname()" ></label>
<br><label>Password:
<input type="password" id="password" onkeyup="passwordcheck()"/></label>
<br><input type="submit" value="New">
</form>
JavaScript:
function checknewaccount() {
var result;
// Because we're actually doing something in each of the
// three functions below, on form validation we want to
// call *all* of them, even if the first one fails, so
// they each color their field accordingly. So instead
// of a one-liner with && as in the previous example,
// we ensure we do call each of them:
result = emailvalid();
result = checkname() && result;
result = passwordcheck() && result;
return result;
}
function emailvalid() {
var element, result;
// Get the email element
element = document.getElementById('email');
// Obviously not a real check, just do whatever your condition is
result = element.value.indexOf('#') > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function checkname() {
var element, result;
// Get the username element
element = document.getElementById('username');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function passwordcheck() {
var element, result;
// Get the username element
element = document.getElementById('password');
// Obviously not a real check, just do whatever your condition is
result = element.value.length > 0;
// Update our label and return the result
updateLabel(element, result);
return result;
}
function updateLabel(node, valid) {
while (node && node.tagName !== "LABEL") {
node = node.parentNode;
}
if (node) {
node.style.color = valid ? "" : "red";
}
}
Live copy

[JavaScript]: How to define a variable as object type?

I am using following code to check whether a check box on my website page is checked or not. But there are several check boxes and I want to use this same function. I want to call this function from a Submit button click and pass the check box name as argument. It should than validate that check box.
function CheckTermsAcceptance()
{
try
{
if (!document.getElementById('chkStudent').checked)
alert("You need to accept the terms by checking the box.")
return false;
}
catch(err)
{
alert(err.description);
}
}
Just pass a parameter to CheckTermsAcceptance(). You also missed a brace after the alert -- there are two statements in that if block, and you'll always execute the return false without it.
function CheckTermsAcceptance(checkboxName)
{
try
{
if (!document.getElementById(checkboxName).checked) {
alert("You need to accept the terms by checking the box.")
return false;
}
}
catch(err)
{
alert(err.description);
}
}
To call this from your submit button, have a function like validateForm that's called on submit. Then simply construct a list of the checkboxes and pass in their IDs to CheckTermsAcceptance.
Note that this sort of validation is handled very smoothly by jQuery and its ilk. For example, here's the jQuery validation plugin.
function CheckTermsAcceptance(element){
try{
if (!element.checked){
alert("You need to accept the terms by checking the box.")
return false;
}
}catch(err){
alert(err.description);
}
}
and you call it like:
CheckTermsAcceptance(document.getElementById('chkStudent'));
is that it?
Sorry for not answering your questions. But you should seriously consider using jQuery and jQuery validate.
You could also use more arguments to allow for different options as well.
function CheckTermsAcceptance()
{
var ctrl = arguments[0];
var valueExpected = arguments[1];
var outputMessage = arguments[2];
if(valueExpected == null) valueExpected = true;
if(outputMessage == null) outputMessage = "You need to accept the terms by checking the box.";
try
{
if(ctrl.checked == valueExpected)
{
Log.Message(outputMessage);
}
}
catch(err)
{
alert(err.description);
}
}
this function will work with a bit of fix up, pass argument and make sure you do both the alert and the return false in the if statement
function CheckTermsAcceptance(checkBox) //added argument
{
try
{
if (!checkBox.checked) { //added block to group alert and fail case
alert("You need to accept the terms by checking the box.")
return false;
}
return true; //added success case
}
catch(err)
{
alert(err.description);
}
}
once you have this in place you can then use it on your form validation like so
<form id="formid" action="" onsubmit="return validate('formid');">
<input type=checkbox name="name" id="name"><label for="name">Name</label>
<input type=checkbox name="name2" id="name2"><label for="name2">Name2</label>
<input type=submit>
</form>
<script>
function validate(formid) {
var form = document.getElementById(formid);
for (var i = 0; i < form.elements.length; i++) {
var elem = form.elements[i];
if (elem.type == 'checkbox' && !CheckTermsAcceptance(elem)) {
return false;
}
}
return true;
}
</script>
i can confirm that this works in firefox 3.5
also jQuery and jQuery.validate make this very easy to implement in a very declarative way.

Categories

Resources