I implemented form in HTML:
<form id="loginForm" action="/?do=login" method="post" >
<table width="50%" border="0">
<tr>
<td colspan="2">
<span id="LoginErr"></span>
<div>Login:</div>
<input id="Login" type="text" maxlength="32" name="Login" value="{VAR %LOGIN}"/>
</td>
</tr>
<tr>
<td valign="bottom">
<span id="PasswordErr"></span>
<div>Passoword:</small></div>
<input id="Password" type="password" maxlength="128" name="Password" value=""/>
</td>
</tr>
<tr>
<td>
Enter
</td>
</tr>
</table>
</form>
This is the check and post function (using jQuery):
function checkLogin()
{
var focused = false;
function report_error(field, err)
{
$('#' + field + 'Err').html(err);
if (!focused)
{
$('#' + field).focus();
focused = true;
}
}
$('#LoginErr').html('');
$('#PasswordErr').html('');
$login = jQuery.trim($('#Login').val());
$password = jQuery.trim($('#Password').val());
if ($login.length == 0)
report_error('Login', 'The login field is empty!');
if ($password.length == 0)
report_error('Password', 'The password field is empty!');
if (!focused)
$('#loginForm').submit();
}
But I have trouble with enter key. When i press this key form is posted without my javascript check.
I need call my function when enter key is pressed and no more action.
Thanx!
Update:
Correct code is:
in form tag need add: onSubmit="return checkLogin()
in javascript if (!focused) $('#loginForm').submit(); need change on return !focused;
Thanks to rdamborsky.
use onSubmit form event:
$(function() {
$('#loginForm').onSubmit = checkLogin;
});
It will be called just before your form's data are actually sent whatever triggers the submit event (click on button, pressing enter within one of fields...)
Related
I'm working on a form validation project that requires multiple input fields connected to a single submit button. I more or less figured the button out, but I'm having an issue getting the functions themselves to work properly. I currently only have three of the eleven fields typed up for testing, but what the page should do is let you know which fields are invalid when there is nothing filled out in them (changing text/background colors, message below, etc).
The issue I'm having is that when the requirements for the first field (Gift Card Number) are met, it acts as though there isn't any issues anywhere, regardless of whether or not the other input fields (First name, Last name) have been filled. They all seem to function correctly if none of the fields are filled, but my concern is that the functions seem to be firing in order and first one to work negates all the ones after (for example, Gift Card prevents First and Last, First prevents Last, etc).
Any ideas where I've gone wrong here? I'll include my html and my javascript. (Yes, I know the html is a bit ugly, I plan to move the material over to a div table later, just trying to get it to function for now) Any help appreciated as always!
HTML
<!DOCTYPE html>
<html lang="en">
<head></head>
<body>
<table>
<tbody>
<tr id="rONE">
<td><h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5></td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
</form>
<tr id="rTWO-1">
<td><h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td><form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4></td>
</form>
</tr>
<tr>
<td><h5 id="recipientMessage"></h5></td></td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
</body>
<footer>
<script src="Form Validation.js"></script>
</footer>
</html>
Javascript
document.getElementById('btn').addEventListener('click', function(){
validateGiftCard();
validateRecipient();
});
function validateGiftCard() {
valid = true;
if ( document.giftForm.giftInput.value == "" )
{
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if ( document.firstForm.firstInput.value == "" )
{
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor="#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor="#fff7f7"
valid = false;
}
return valid;
}
document.getElementById('btn').addEventListener('click', function(e) {
var v1 = validateGiftCard();
var v2 = validateRecipient();
console.log(v1, v2);
if (!v1 || !v2)
e.preventDefault();
});
function validateGiftCard() {
valid = true;
if (document.giftForm.giftInput.value == "") {
giftMessage.innerHTML = "This field is required";
document.getElementById("rONE").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
function validateRecipient() {
valid = true;
if (document.firstForm.firstInput.value == "") {
recipientMessage.innerHTML = "This field is required";
document.getElementById("rTWO-1").style.backgroundColor = "#fff7f7"
document.getElementById("rTWO-2").style.backgroundColor = "#fff7f7"
valid = false;
}
return valid;
}
<table>
<tbody>
<tr id="rONE">
<td>
<h4>Gift Card Amount</h4>
<form name="giftForm" onsubmit="return validateGiftCard()" method="post" id="GiftCardForm">
<input type="text" name="giftInput">
<h5 id="giftMessage"></h5>
</form>
</td>
<input type="submit" value="Submit" style="display:none" />
<td></td>
</tr>
<tr id="rTWO-1">
<td>
<h4>Recipient's name</h4>
</td>
<td> </td>
</tr>
<tr id="rTWO-2">
<td>
<form name="firstForm" onsubmit="return validateRecipient()" method="post">
<input type="text" name="firstInput">
<br>
<h4>First</h4>
</form>
</td>
<td>
<form name="lastForm" method="post">
<input type="text" name="lastInput">
<br>
<h4>Last</h4>
</form>
</td>
</tr>
<tr>
<td>
<h5 id="recipientMessage"></h5>
</td>
<td> </td>
</tr>
</tbody>
</table>
<button type="submit" id="btn" form="GiftCardForm" value="Submit">Submit</button>
I am trying to submit a form in that I have Addmore functionality in it.
Example: I have entered name and then I have used addmore button so now remove appeared in second tr.
When I click the remove that tr is removed now, but when click the form submit button it is skipping the phone number validation,
so to remove the functionality is throwing out validation.
My html somewhat looks like this:
<form>
Name<input type="text" name="name" id="name" placeholder="Name Your Name "/>
<table class="skillsTable" id="jobSkills">
<tbody>
<tr class="gdskilltr">
<td><button type="button" class="addSkills"> Add Skill</button></td>
<td><button type="button" class="removeSkill"> Remove Skill</button></td>
</tr>
</tbody>
</table>
phone<input type="text" name="phone" id="phone" placeholder="enter Your phone "/>
<button type="submit" id="JobSubmit">Submit</button>
</form>
And here my Javascript validation starts:
var skillcount = 1;
$(".addSkills").click(function () {
$('#jobSkills tr:last').after('<tr class="gdskilltr "><td></td></tr>');
skillcount++;
});
$("#jobSkills").on('click', '.removeSkill', function () {
$(this).parent().parent().remove();
});
$("#JobSubmit").click(function () {
if ($("#name").val() == '') {
$("#warning_message").html('Please Enter name');
$("#name").focus();
return false;
}
if ($("#phone").val() == '') {
$("#warning_message").html('Please Enter name');
$("#phone").focus();
return false;
}
}
I have a login form with the following fields -
Username
Password
Return Failure
Direct Login
When I click on submit all the fields are appended in the URL and it hits a JSP file.
After this,
Scenario 1: If login is a success, it is redirected to success page. This works
Scenario 2: If login fails, it is redirected to the return failure URL value passed as parameter. While redirecting it does not give any response.
Question -
1. How can I differentiate between loading a fresh form and form loaded after redirection?
2. I have to display a warning for invalid username and password before redirecting the page to returnfailure value and not during a fresh load of form.How can I do this?
Below is the code -
**HTML**
<form name="formlogin" method="get" onsubmit="return ValidateForm();" class="form-wrapper">
<table>
<tr>
<td>
<label class="service-lable" style="font-family:Verdana;">Username</label>
</td>
<td>
<input type="email" name="username" maxlength="30" size="30" class="required"/> <br/><br/>
</td>
</tr>
<tr>
<td>
<label class="service-lable" style="font-family:Verdana;">Password</label>
</td>
<td>
<input type="password" name="password"maxlength="30" size="30" class="required"/> <br/><br/>
</td>
</tr>
<tr>
<td>
<input type="hidden" name="directlogin" id="directlogin" value="1"/>
</td>
<td>
<input type="hidden" name="returnfailure" id="returnfailure" value="http://www.google.com"/>
</td>
</tr>
<tr>
<td>
<input type="submit" name="login" value="" class="button_add" />
</td>
</tr>
</table>
</form>
**Javascript**
<script>
function emailcheck(str) {
var at="#";
var dot=".";
var lat=str.indexOf(at);
var lstr=str.length;
var ldot=str.indexOf(dot);
if (lat ==-1 || lat == 0 || lat == lstr){
return false;
}
if (ldot==-1 || ldot==0 || ldot == lstr){
return false;
}
if (str.indexOf(at,(lat+1))!=-1){
return false;
}
if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot){
return false;
}
if (str.indexOf(dot,(lat+2))==-1){
return false;
}
if (str.indexOf(" ")!=-1){
return false;
}
return true;
}
function ValidateForm(){
var emailID=document.forms["formlogin"].username;
var username=document.forms["formlogin"].username.value;
username=username.toLowerCase();
var password=document.forms["formlogin"].password.value;
if ((emailID.value==null)||(emailID.value == "")){
// alert("Please Enter your Email ID");
emailID.focus();
return false;
}
if (emailcheck(emailID.value)== true){
document.forms["formlogin"].action = "http://www.test.com/login.jsf";
return true;
} else {
alert ('Please enter the valid Email ID');
return false ;
}
}
</script>
TJ is on the right track. Usually here you want to have the server be able to pass the contents of the form as well as the error to the client when the page loads (even the first time). If you want to do this entirely client side, perhaps you could have the form submit take the place of a javascript ajax request. The javascript can then interpret the server response and then either populate the page with the error message or redirect to the success page.
I am experimenting with a form that has a text field and a check box. I am a designer and not a developer. I have successfully gotten the text box to Validate, but I have pasted in code for the checkbox, which for some reason either cancels out the validation or returns an error at the paypal server. Can anyone suggest a few lines of code to validate the checkbox "terms"? The textbox is called "os0"
<form action="https://www.paypal.com/cgi-bin/webscr" method="post" target="_top" id="myForm" onSubmit="return validateForm()" >
<input type="hidden" name="cmd" value="_s-xclick">
<input type="hidden" name="hosted_button_id" value="AXNKKDCZLVHM4">
<table width="100%" border="0">
<tr>
<th scope="row"><input type="hidden" name="on0" value="Your RCEH Account Number:" />
Your RCEH Account Number:
</th>
<td>
<input type="text" name="os0" maxlength="200" />
</td>
</tr>
<tr>
<th scope="row"> </th>
<td><label>
<input type="checkbox" name="terms" id="terms" />
Agree to terms and conditions</label>
</td>
</tr>
</table>
<input type=submit value="Proceed to secure server">
<img alt="" border="0" src="https://www.paypalobjects.com/en_US/i/scr/pixel.gif" width="1" height="1">
</form>
</div>
</div>
<script>
function validateForm() {
var x=document.forms["myForm"]["os0"].value;
if (x==null || x==""){
alert("RCEH account number must be filled out");
return false;
}
}
</script>
Assuming that you only want your checkbox to be checked, below there is the code you need, and this is a working JSFiddle.
function validateForm() {
var form = document.getElementById("myForm"); //get the form element via ID
if (form.os0.value == "")
{
alert("RCEH account number must be filled out");
return false;
}
if (!form.terms.checked) { // checks if the checkbox called "terms" is checked; if it is not, alerts a message and return false
alert("Terms must be read and approved");
return false;
}
return true; //if everything is okay, return true and submit the form
}
I used the following code:
<script type="text/javascript">
function validate() {
if ((document.changepass.newpassword.value != '') &&
(document.changepass.retypenewpassword.value ==
document.changepass.newpassword.value)){
document.changepass.retypenewpassword.blur();
document.changepass.submit();
}
}
</script>
<form name="changepass" method="POST" action="changepassword.jsp" onsubmit="return validate();">
<table align="center">
<tr>
<td>New Password:</td>
<td><input type="password" name="newpassword" size="20"
style="width: 145px" maxlength="10"></td>
</tr>
<tr>
<td>Retype New Password:</td>
<td><input type="password" name="retypenewpassword" size="20"
style="width: 144px" maxlength="10"></td>
</tr>
<tr>
<td><input type="submit" value="Change Password" name="operation" ></td>
<td><input type="reset"></td>
</tr>
</table>
</form>
but when I'm giving unmatched entry then also it getting changed.i mean the validate function is not getting called.
plz help
in hope
robin
Your form will submit no matter what, because you are not returning false from the validating function on error. It should be:
function validate() {
var d = document.changepass;
if((d.newpassword.value != '') && (d.retypenewpassword.value == d.newpassword.value)) {
return true;
}
return false;
}
At current, you are not specifying a return value for validate(), and it is interpreted as always returning true, so the form gets submitted. You don't need to call submit() from your function, simply return true if everything is ok.
The onsubmit handler on your <form> is looking for a return value, but is not given one from your validate function. Instead of calling submit() in the function, you should return true or false, depending on if the form validates (if the function returns false, that is equivalent to onsubmit="false", which will cancel the submission):
function validate()
{
if ((document.changepass.newpassword.value != '') && (document.changepass.retypenewpassword.value != document.changepass.newpassword.value))
{
// A password is given but it doesn't match
// Perhaps you want to alert() an error message here to tell the user why the form doesn't validate?
return false;
}
return true;
}