js function call help needed - javascript

i have the code as shown below,
this is the html part.
<html>
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script src="regi.js" ></script>
</head>
<body class="regbody">
<form align="center" method="POST" action="submit()" name="regform">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="ip" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="ip" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="ip" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="ip" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
</body>
and the js code is below for the Submit function
function Submit(){
var fname = document.form.regfname.value,
uname= document.form.reguname.value,
fpassword = document.form.regpwd.value,
cfpassword= document.form.cregpwd.value;
if( uname == "" || uname == "Enter Desired Username")
{
document.form.reguname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if( fname == "" || fname == "Enter name")
{
document.form.regfname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if(fpassword == "" || fpassword == "Select password" )
{
document.form.regpwd.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (!(cfpassword.equals(fpassword)) )
{
document.form.cregpwd.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if(fname != '' && fpassword != '' && cfpassword != '' && uname!= ''){
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
}
when i click the regiter button, it says this webpage has npt been found.
i am new to javascript and need help. thanks in advance.

Yet Another Update - I realised there are errors in your Javascript code for referencing DOM objects (as well as a typo in your validation logic), below are the working modified code. In short, I have added id's to the form elements for referencing, and in your validation logic, you should be check Select Password instead of Select password.
The HTML form
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" id="regform" onsubmit="return Submit()">
<div id="regpgdiv">
<span class="indextext">Fill in the details below to get registered! </span><br><br><br><br><br><br>
<input type="text" name="regfname" id="fname" value="Enter name" onfocus="if(this.value == 'Enter name') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter name'; }" /> <br><br>
<input type="text" name="reguname" id="uname" value="Enter Desired Username" onfocus="if(this.value == 'Enter Desired Username') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Enter Desired Username'; }" /> <br><br>
<input type="password" name="regpwd" id="regpwd" value="Select Password" onfocus="if(this.value == 'Select Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Select Password'; }" /> <br><br>
<input type="password" name="cregpwd" id="cregpwd" value="Re-enter Password" onfocus="if(this.value == 'Re-enter Password') { this.value = ''; }" onblur="if(this.value == '') { this.value = 'Re-enter Password'; }" /> <br><br>
<input type="submit" value="Register" id="credsub" >
</div>
</form>
JS
function Submit() {
var fname = document.getElementById("fname");
var uname= document.getElementById("uname");
var fpassword = document.getElementById("regpwd");
var cfpassword= document.getElementById("cregpwd");
if (uname.value == "" || uname.value == "Enter Desired Username") {
uname.focus() ;
document.getElementById("errorBox").innerHTML = "enter the username";
return false;
}
if (fname.value == "" || fname.value == "Enter name") {
fname.focus();
document.getElementById("errorBox").innerHTML = "enter the first name";
return false;
}
if (fpassword.value == "" || fpassword.value == "Select Password" ) {
fpassword.focus();
document.getElementById("errorBox").innerHTML = "enter the password";
return false;
}
if (cfpassword.value != fpassword.value) {
cfpassword.focus();
document.getElementById("errorBox").innerHTML = "doesnt match";
return false;
}
if (fname.value != '' && fpassword.value != '' && cfpassword.value != '' && uname.value != '') {
document.getElementById("errorBox").innerHTML = "form submitted successfully";
}
return true;
}
Updated - Thanks Useless Code for the helpful suggestion, I have modified the code accordingly to use onSubmit instead of the onClick event.
Your HTML code should be:
<form align="center" method="POST" action="TARGET-PAGE-TO-HANDLE-DATA" name="regform" onsubmit="return Submit();">
The action attribute specifies the target page to handle the form data. And the onSubmit attribute specifies the Javascript function to be executed when the submit button in the form is clicked.

As already stated in a comment, onsubmit is much more appropriate in this situation. The JavaScript placed in an onclick attribute will fire when the HTML element is clicked, but for a form you actually want code that executes on submission. So:
<form align="center" method="POST" action="self" name="regform" onsubmit="Submit()">
would be closer. However, it's generally considered poor practice to use the "on" attributes to handle events in JavaScript. For one, it mixes your JavaScript with your semantic HTML, which can be make debugging harder an mixes separate concerns. But it also means that whatever you use in the "on" attributes has to be in the global scope, which can become problematic fast. Consider if you had multiple forms on the page; how would you designate the submit functions for each?
A more solid way of performing this is to put your function in an event listener, e.g.:
function Submit() {
// rest of your code here
}
document.form.regform.addEventListener('submit', Submit, false);
Here the addEventListener method takes an event type string first and a function to execute when that event occurs second. The MDN article on addEventListener has more.

Related

How to validate empty value using javascript?

Here is html code for text field what to check for empty/null values
function myFormValidation() {
alert("HI");
var name = document.getElementById("name").value;
alert(name);
if (name == null || name == " ") {
document.getElementById("inp1").innerHTML = "Enter your name please";
} else {
document.myForm.submit();
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" name="inp1" />
<input type="button" value="Register" onclick=" myFormValidation()" />
I want to validate using innerHtml, but my js is not getting called.
I guess removing the space between " " may work
your code
if(name==null || name ==" " ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
change to
if(name==null || name =="" ){
document.getElementById("inp1").innerHTML = "Enter your name please";
}
You might like to validate the input edit through the help of regular expressions
if ( name == null || /\s*/g.test(name) )
{
document.getElementById("inp1").innerHTML = "Enter your name please";
}
The expression \s* covers both the empty string as well as the input consists of multiple blank spaces, such as " " for example
I'm not really familiar with JavaScript/jQuery but I think this is what you're looking for. I've changed your input for the message to label because your type is hidden which also means that users will not be able to see the message at all.
Also, you didn't include the id attribute for your inp1 so it's impossible to use getElementbyId().
function myFormValidation() {
if (document.getElementById("name").value == "") {
document.getElementById("inp1").innerHTML = "Enter your name please";
}
else {
var name = document.getElementById("name").value;
alert("HI");
alert(name);
document.myForm.submit();
}
}
Name:
<input type="text" name="name" id="name" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<label id="inp1"></label>
Here is example:
function myFormValidation() {
var user = document.getElementById("name").value;
if (user === "") {
document.getElementById("body").innerHTML = "Enter your name please";
} else {
document.getElementById("body").innerHTML = user + " " + "How are you..!";
}
}
Name
<input type="text" name="name" id="name" />
<input type="hidden" />
<input type="button" value="Register" onclick=" myFormValidation()" />
<div id="body"></div>

javascript form validation doesn't work even though everything seems okay (JS is not disabled in browser)

I have this form:
<form action="../scrapll_m_nonstatic/process/reg/signup_process.php" method="post" name="signUp" onsubmit="return signUpVal()">
<div id="fieldHolder">
<input type="text" id="accountFieldFirstName" class="accountField" name="firstName" placeholder="First Name" />
<input type="text" id="accountFieldLastName" class="accountField" name="lastName" placeholder="Last Name" />
<input type="text" id="accountFieldUsername" class="accountField" name="username" placeholder="Username" />
<input type="text" id="accountFieldEmail" class="accountField" name="email" placeholder="Email Address" />
<input type="password" id="accountFieldPassword" class="accountField" name="password" placeholder="Password" />
</div>
<div id="subFooter">
<a data-ftrans="slide reverse" href="index.php" id="signUpButton">Sign In</a>
<a data-ftrans="slide" href="forgot.php" id="forgotButton">Forgot password</a>
</div>
<div id="footer">
<input type="submit" id="signIn" value="Sign Up" />
</form>
And I have this JS form validation script to check if the forms are empty:
function signUpVal()
{
var firstName = document.forms["signUp"]["firstName"].value;
var lastName = document.forms["signUp"]["lastName"].value;
var userName = document.forms["signUp"]["userName"].value;
var email = document.forms["signUp"]["email"].value;
var password = document.forms["signUp"]["password"].value;
if (firstName == null || lastName == "" || lastName == null || lastName == "" || userName == null || userName == "" || email == null || email == "" || password == null || password = "")
{
alert("Please fill out the form completely");
return false;
}
}
It doesn't do anything and goes directly to the action PHP script. How can I fix that?
You have two mistakes:
1). Name of the user name input does not match in JS code. Fix it to this:
<input type="text" name="userName" id="accountFieldUsername" class="accountField" placeholder="Username" />
instead of name="username"
2). Check your values like this:
if (firstName == "" || lastName == "" || userName == "" || email == "" || password == "") {
alert("Please fill out the form completely");
return false;
}
Also you don't need == null checks because form element value cannot be null, it's empty string if left blank.
Demo: http://jsfiddle.net/tn4A6/
I think this might be your problem.
You are using assignment operator = instead of comparison operator ==.
Your if condition should be:
if (firstName == null || lastName == "" || lastName == null || lastName == "" || userName == null || userName == "" || email == null || email == "" || password == null || password == "")
{
alert("Please fill out the form completely");
return false;
}
The last "=" (as opposed to "==") in the if (firstName == null .. etc ) statement was seen as a syntax error by IE, so the whole script didn't compile.
Firefox said the same thing, but surprisingly neither of them highlighted it with a popup. Only visible when you click F12 for debugger.
This meant the function signUpVal() didn't compile, so it didn't exist so far as the page was concerned - so the form just submitted.
dfsq's answer provides the rest

Javascript with html form validation not working

i'm trying to validate a form using a simple javascript script however it is not working, can anyone tell me what is wrong with my code? (sorry for my vague question)
JS code:
<script type="text/javascript">
function validation()
{
var fName=document.forms["teacherReg"]["firstname"].value;
var lName=document.forms["teacherReg"]["lastname"].value;
var uName=document.forms["teacherReg"]["username"].value;
var pWord=document.forms["teacherReg"]["password"].value;
var cPWord=document.forms["teacherReg"]["confirmpassword"].value;
if (fName="" || lName="" || uName="" || pWord="")
{
alert("Not a valid entry");
return false;
}
}
</script>
html form:
<form name="teacherReg" action="" method="POST" onsubmit="return validation();">
1. First name:
2. Last name:<br/><input type="text" name="firstname" id="firstname" />
<input type="text" name="lastname" id="lastname" /><br/><br/>
3. Desired Username:
<br/><input type="text" name="username" id="username" /><br/><br/>
4. Desired Password:
5. Confirm Password:<br/><input type="password" name="password" id="password" />
<input type="password" name="confirmpassword" id="confirmpassword" /> <br/><br/>
<center><input type="submit" value="Register" name="submitbutton" class="button" /></center>
</form>
I expect it to return false if any of the fields "fName, lName, uName, pWord" are blank, however it is always returning true
The problem is that you confused = (assignment operator) operator with == (comparison operator):
if (fName = "" || lName = "" || uName = "" || pWord = "") {
It should be
if (fName == "" || lName == "" || uName == "" || pWord == "") {
Fixed demo: http://jsfiddle.net/49xDH/
This is the problem:
if (fName=="" || lName=="" || uName=="" || pWord=="")
= is assignment operator , where == is comparison operator. use == for comparing values.
Use the comparison operator == instead of the assignment operator =.
Please try to use the ID instead of the form object.
function validation(){
var username = document.getElementById('username').value;
// etc.
}

How do I disable form dropdown option using javascript

I'm trying to disable the "name" text field in the form when "Choose" is selected in the drop down after the page loads (it's disabled when the page loads) ie after I've chosen one of the other two options that disable or enable that field, when I return to "Choose" i'd like the same field to disable. I can't see why the javascript I've written would prevent this from happening. Thanks!
<script type="text/javascript">
function clickclear(thisfield, defaulttext) {
if (thisfield.value === defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (thisfield.value === "") {
thisfield.value = defaulttext;
}
}
function checkPickup() {
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
/* Reset form values */
form.name.value = "His/her name";
}
}
</script>
<script type="text/javascript">
function validate(form) {
var errmsg = "Oops, you're required to complete the following fields! \n";
// Various other form validations here
// Validate "Pickup"
if (form.os0.value === "") {
errmsg = errmsg + " - Choose pickup or delivery\n";
}
// Validate "phone"
if (form.phone.value === "" || form.phone.value === "Mobile's best!") {
errmsg = errmsg + " - Your phone number\n";
}
if (form.os0.value != "Pickup from Toowong, Brisbane") {
// Validate "name"
if (form.name.value === "" || form.name.value === "His/her name") {
errmsg = errmsg + " - His/her name\n";
}
}
// Alert if fields are empty and cancel form submit
if (errmsg === "Oops, you're required to complete the following fields! \n") {
form.submit();
} else {
alert(errmsg);
return false;
}
}
</script>
</head>
<body>
<form name="form" action="https://www.paypal.com/cgi-bin/webscr" method="post" onSubmit="return validate(form)">
<p class="row">
<input type="hidden" name="on0" value="Pickup and delivery" />Pickup and delivery<br />
<select name="os0" onchange="checkPickup()">
<option value="" selected >Choose</option>
<option value="Pickup from Toowong, Brisbane">Pickup from Toowong, Brisbane $1.00 AUD</option>
<option value="Brisbane +$23.60">Brisbane +$23.60 =$1.00 AUD</option>
</select>
</p>
<p class="row">Your daytime phone number<br />
<input type="text" name="phone" value="Mobile's best!" onclick="clickclear(this, 'Mobile\'s best!')" onblur="clickrecall(this,'Mobile\'s best!')" />
</p>
<p class="row">Recipient's name<br />
<input style="color: #ccc" class="name" type="text" name="name" value="His/her name" onclick="clickclear(this, 'His/her name')" onblur="clickrecall(this,'His/her name')" disabled />
</p>
<input name="custom" type="hidden" />
<input type="hidden" name="currency_code" value="AUD" />
<input class="button" type="image" src="https://www.paypalobjects.com/en_AU/i/btn/btn_buynowCC_LG.gif" border="0" name="submit" alt="PayPal — The safer, easier way to pay online." />
<img alt="" border="0" src="https://www.paypalobjects.com/en_AU/i/scr/pixel.gif" width="1" height="1"> -->
</form>
</body>
</html>
This may be a simple misunderstanding of what you've written:
if (form.os0.value != "Pickup from Toowong, Brisbane" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
translates to the following in plain english:
If the value is NOT "Pickup from Toowong, Brisbane", enable the field, otherwise disable it.
which is equivalent to:
ONLY disable the field when the value is "Pickup from Toowong, Brisbane".
I believe the logic you're looking for is:
if (form.os0.value == "Brisbane +$23.60" ) {
form.name.disabled = false; form.name.style.color = '#333';
} else {
form.name.disabled = true; form.name.style.color = '#CCC';
//
}
though it might be prettier to code this with a switch statement due to the involvement of specific cases.
See DEMO
did you intend to type double equal to (==) or is the triple equal to (===) a typo in the question? Based on looking at your code, it looks to me like you need a double equal to (==) not a triple. I think triple may mean something else.

jQuery form validation issue

I'm not using any jQuery plugin to validate the form, just plain jQuery. My issue is that after it validates all the input elements, even if it shows the error message to the user, it will still submit the form without the user correcting the error.
To elaborate, my form has 3 input elements. with jQuery validation, if all the 3 elements are empty, and the user clicks on the Submit button, it will throw an error highlighting the first element. If the user does not correct the error, but clicks on the submit button again, it will highlight the second element [with the first input element still highlighted]. Likewise for the 3rd element. Now if the user without correcting the error (that is, the input elements are still highlighted) clicks on the submit button again, it will submit the form. Ideally, it should keep on highlighting the first input element till the user corrects his error and then validate the 2nd input element and so on. .and this is what I want to do.
jQuery code:
$(function() {
/*Form Validation*/
$("#name")
.focus(function() {
if ($(this).val() == "Your Name" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Name");
}
})
.keyup(function() {
$("#name").val($(this).val());
}),
$("#email")
.focus(function() {
if ($(this).val() == "Your Email" || $(this).val() == "Field cannot be blank" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Email");
}
})
.keyup(function() {
$("#email").val($(this).val());
}),
$("#msg")
.focus(function() {
if ($(this).val() == "Your Message" || $(this).val() == "You forgot to enter your message" ) {
$(this).val("");
$(this).css("background", "#FFF");
}
})
.blur(function(){
if ($(this).val() == "") {
$(this).val("Your Message");
}
})
.keyup(function() {
$("#msg").val($(this).val());
})
});
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name") {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email") {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message") {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
. .html:
<form action="somepage.php" method="post" id="contactform">
<div class="container">
<div class="field">
<input type="text" tabindex="1" value="Your Name" name="name" id="name" /><br />
</div>
<div class="field">
<input type="text" tabindex="2" value="Your Email" name="name" id="email" /><br />
</div>
<div class="field">
<textarea tabindex="3" name="msg" id="msg">Your Message</textarea><br />
</div>
<input type="button" onclick="return checkForm('contactform');" id="sb" value="Submit" class="submitbtn" />
</div>
</form>
Your checkform function behaves like it should.
However here is a possible correction
function checkForm(form) {
var cssObj = {
'background-color' : 'red',
'border' : 'green'
}
if ($("#name").val() == "" || $("#name").val() == "Your Name" || $("#name").val() == 'Field cannot be blank' ) {
$("#name").css(cssObj);
$("#name").val('Field cannot be blank');
return false;
}
else if ($("#email").val() == "" || $("#email").val() == "Your Email" || $("#email").val() = 'Field cannot be blank' ) {
$("#email").css(cssObj);
$("#email").val('Field cannot be blank');
return false;
}
else if ($("#msg").val() == "" || $("#msg").val() == "Your Message" || $("#msg").val() == 'You forgot to enter your message' ) {
$("#msg").css(cssObj);
$("#msg").val('You forgot to enter your message');
return false;
}
else {
return true;
}
}
Please look at http://en.wikipedia.org/wiki/Idempotence too.

Categories