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>
Related
I have a webform in which a user has to fill in details. I am using Javascript and html in order to do multiple input validation with regular expressions. I have part of the javascript + html code below. The variables a-g are regexes of each input field required.
I created an empty Array called Err_arr to stored the errors that has met the conditions (e.g. if the user does not input anything / if the user does not fulfil the required format of input) The error message will be pushed into the array. The last if statement will be used to check whether the array is not empty, hence it will print out all the error messages on multiple lines depending on what the conditions are.
function validateForm() {
var cname = document.getElementById("cname").value;
var odate = document.getElementById("odate").value;
var cno = document.getElementById("cno").value;
var ccn = document.getElementById("ccn").value;
var expm = document.getElementById("expm").value;
var expy = document.getElementById("expy").value;
var cvv = document.getElementById("cvv").value;
var Err_Arr = [];
var a = /^(\w\w+)\s(\w+)$/;
var b = /^(0?[1-9]|[12][0-9]|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/;
var c = /[0-9]{8}/;
var d = /[0-9]{16}/;
var e = /0[0-1]1[0-9]){2}/;
var f = /[0-9]{4}/;
var g = /[0-9]{3}/;
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (odate == null || odate == "") {
Err_Arr.push("Please Enter Info - Order Date");
}
if (cno == null || cno == "") {
Err_Arr.push("Please Enter Info - Contact No");
}
if (ccn == null || ccn == "") {
Err_Arr.push("Please Enter Info - Credit Card Number");
}
if (expm == null || expm == "") {
Err_Arr.push("Please Enter Info - Expiry Month");
}
if (expy == null || expy == "") {
Err_Arr.push("Please Enter Info - Expiry Year");
}
if (cvv == null || cvv == "") {
Err_Arr.push("Please Enter Info - CVV No");
}
if (cname.test(a) == false) {
Err_Arr.push("Enter correct input");
}
if (odate.test(b) == false) {
Err_Arr.push("Enter correct input");
}
if (cno.test(c) == false) {
Err_Arr.push("Enter correct input");
}
if (ccn.test(d) == false) {
Err_Arr.push("Enter correct input");
}
if (expm.test(e) == false) {
Err_Arr.push("Enter correct input");
}
if (expy.test(f) == false) {
Err_Arr.push("Enter correct input");
}
if (cvv.test(g) == false) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \> Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \> Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \> Credit card number: (e.g. 123456789) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \> Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \> Expiry date - year part (yyyy): <input id="expy"
type="text" name="expy" autocomplete="off"> <br \> CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I expect the whole web form to give me a whole list of alerts in the conditions that I did not satisfy for the if statements. Instead, my code is not running at all.
The intent of your code is correct. Reason why alerts doesn't show:
A syntax error in var e. notice the missing pair of the parenthesis. should be /0[0-1]1([0-9]){2}/;
.test() is used incorrectly. please refer to w3schools tutorial how to use test. Basically, test() is a method in the Regexp object in javascript. So it should be like regexObject.test(yourString)
Fixing all that most likely will make your code run without issues.
function validateForm() {
var cname = document.getElementById("cname").value;
var Err_Arr = [];
var a = new RegExp(/^(\w\w+)\s(\w+)$/);
if (cname == null || cname == "") {
Err_Arr.push("Please Enter Info - Customer Name");
}
if (!a.test(cname)) {
Err_Arr.push("Enter correct input");
}
if (Err_Arr.length > 0) {
alert(Err_Arr.join("\n"));
}
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name:<input id="cname" type="text" name="cname" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
You have some mistakes:
an invalid regex for e as it has unbalanced parentheses
Strings don't have a test method; regexes do
The suggestion for the credit card number in your HTML would not pass the corresponding regex (that requires 16 digits)
There are also some shorter ways to do things:
if (cname == null || cname == "")
can be just:
if (!cname)
More importantly, you have a lot of code repetition. You could avoid that by doing things in a loop:
function validateForm() {
var validations = [
{ input: "cname", regex: /^(\w\w+)\s(\w+)$/, name: "Customer name" },
{ input: "odate", regex: /^(0?[1-9]|[12]\d|3[01])[\/\-](0?[1-9]|1[012])[\/\-]\d{4}$/, name: "Order date" },
{ input: "cno", regex: /^\d{8}$/, name: "Contact No" },
{ input: "ccn", regex: /^\d{16}$/, name: "Credit Card Number" },
{ input: "expm", regex: /^0?[1-9]|1[012]$/, name: "Expiry Month" }, // Correct regex
{ input: "expy", regex: /^\d{4}$/, name: "Expiry Year" },
{ input: "cvv", regex: /^\d{3}$/, name: "CVV No" }
];
var errors = validations.map(({input, regex, name}) => {
var value = document.getElementById(input).value;
if (!value) return "Please Enter Info - " + name;
if (!regex.test(value)) return "Enter correct input - " + name;
}).filter(Boolean);
if (errors.length) {
alert(errors.join("\n"));
return false;
}
return true;
}
<h2>Part 3 - Javascript with Alert Box</h2>
<form method="get" onsubmit="return validateForm()" name="form1">
Customer name: <input id="cname" type="text" name="cname" autocomplete="off"> <br \>
Order date: <input id="odate" type="text" name="odate" autocomplete="off"> <br \>
Contact number: (e.g. 98765432) <input id="cno" type="text" name="cno" autocomplete="off"> <br \>
Credit card number: (e.g. 1234567890123456) <input id="ccn" type="text" name="ccn" autocomplete="off"> <br \>
Expiry date - month part (mm): <input id="expm" type="text" name="expm" autocomplete="off"> <br \>
Expiry date - year part (yyyy): <input id="expy" type="text" name="expy" autocomplete="off"> <br \>
CVV Number (e.g. 123): <input id="cvv" type="text" name="cvv" autocomplete="off"> <br \>
<input type="submit" value="Submit">
</form>
I am trying to make a form. I want it to check the radio buttons to see if they have been clicked, and if not to have a message to the user to check one.
I tried to just enter it, then I tried to continue my else if statements with it (got error messages), then I tried making a function within the onsubmit function (it simply didn't initiate), then I tried making a function outside of the onsubmit function and am trying to call it, but it does not initiate. I've even tried moving the functions on top or below the onsubmit function.
I made the submitYesCancel to see if the problem was with the radioB function, but neither function will initiate.
I'm hopelessly stuck. Please help.
Here is the code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<title></title>
<script type="text/javascript">
/* <![CDATA[ */
function confirmPassword()
{
if (document.forms[0].password_confirm.value != document.forms[0].password.value)
{
window.alert("You did not enter the same password!");
document.forms[0].password.focus();
}
}
function submitForm()
{
submitYesCancel();
if (document.forms[0].name.value == ""
|| document.forms[0].name.value == "Your Name")
{
window.alert("You must enter your name.");
return false;
}
else if (document.forms[0].emailAddress.value == ""
|| document.forms[0].emailAddress.value == "Your Email")
{
window.alert("You must enter your email address.");
return false;
}
else if (document.forms[0].password.value == ""
|| document.forms[0].password_confirm.value == "")
{
window.alert("You must enter a password.");
return false;
}
else if (document.forms[0].sq.value ==""
|| document.forms[0].sq.value == "Your Security Answer")
{
window.alert("You must enter a security answer.");
return false;
}
radioB();
return true;
}
function submitYesCancel()
{
var submitForm = window.confirm("Are you sure you want to submit the form?");
if (submitForm == true)
{
return true;
return false;
}
}
function radioB()
{
var radioButton = false;
for (var i = 0; i < 4; ++i)
{
if (document.forms[0].special_offers[i].checked == true)
{
radioButton = true;
break;
}
}
if (radioButton != true)
{
window.alert("You must select a radio button.");
return false;
}
}
function confirmReset()
{
var resetForm = window.confirm("Are you sure you want to reset the form?");
if (resetForm == true)
return true;
return false;
}
/* ]]> */
</script>
</head>
<body>
<form>
<h2>Personal Information</h2>
<p>Name:<br />
<input type = "text" name = "name" placeholder = "Your Name" size = "50"/></p>
<p>Email Address:<br />
<input type = "text" name = "emailAddress" placeholder = "Your Email" size= "50" /></p>
<h2>Security Information</h2>
<p>Please enter a password of 8 characters or less: <br />
<input type = "password" name = "password" maxlength = "8" /></p>
<p>Confirm password<br />
<input type = "password" name = "password_confirm" size = "50" onblur = "confirmPassword();" /></p>
<p>Please Select a Security Question from the Drop Down List.<br />
<select name = "Security Question">
<option value = "mother">What is your Mother's maiden name?</option>
<option value = "pet">What is the name of your pet?</option>
<option value = "color">What is your favorite color?</option>
</select></p>
<p><input type = "text" name = "sq" placeholder = "Your Security Answer" size = "50" /></p>
<h2>Preferences</h2>
<p>Would you like special offers sent to your email address?<br />
<input type = "radio" name = "radioButton" value = "Yes" />Yes<br />
<input type = "radio" name = "radioButton" value = "No" />No<br /></p>
<p>Are you interested in special offers from: <br />
<input type = "checkbox" name = "sCheckboxes" value = "e" />Entertainment<br />
<input type = "checkbox" name = "sCheckboxes" value = "b" />Business<br />
<input type = "checkbox" name = "sCheckboxes" value = "s" />Shopping<br /></p>
<button onclick="return submitForm();">Submit</button>
<button onclick="return confirmReset();">Reset</button>
</form>
</body>
</html>
The reason that it does not work because your Javascript is completely wrong.
}
radioB();
else // <--- what does it mean?
return true;
And
else if (radioButton ! = true) {
// <-- you have else if, but there is no if block and it is != not ! =
Next time when your Javascript does not work, try to see the error first. You can easily do this in Google Chrome. Hit Ctrl + Shift + J, go to Console tab. Then, fix each error when you encounter it until there is no more error.
I'm working on a PHP form for inputting user information. I have these 3 important fields: First Name, Last Name, and E-mail. What I need to do is to set the E-mail automatically when the user enters the first two fields and before saving. For example when the user types 'First' in the First Name and 'Last' in the Last Name fields, the E-mail field should automatically show First.Last#example.com.
The code is already written and this is the part I'm working on:
echo '<TABLE ><TR><TD >'.TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','<FONT color=red>'._('First').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]',''._('Middle').'','class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.TextInput($student['LAST_NAME'],'students[LAST_NAME]','<FONT color=red>'._('Last').'</FONT>','size=12 class=cell_floating maxlength=50 style="font-size:14px; font-weight:bold;"').'</TD><TD>'.SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]',''._('Suffix').'',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"').'</TD></TR></TABLE>';
else
echo '<DIV id=student_name><div style="font-size:14px; font-weight:bold;" onclick=\'addHTML("<TABLE><TR><TD>'.str_replace('"','\"',TextInput($student['FIRST_NAME'],'students[FIRST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['MIDDLE_NAME'],'students[MIDDLE_NAME]','','size=3 maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',TextInput($student['LAST_NAME'],'students[LAST_NAME]','','maxlength=50 style="font-size:14px; font-weight:bold;"',false)).'</TD><TD>'.str_replace('"','\"',SelectInput($student['NAME_SUFFIX'],'students[NAME_SUFFIX]','',array('Jr.'=>'Jr.','Sr.'=>'Sr.','II'=>'II','III'=>'III','IV'=>'IV','V'=>'V'),'','style="font-size:14px; font-weight:bold;"',false)).'</TD></TR></TABLE>","student_name",true);\'>'.$student['FIRST_NAME'].' '.$student['MIDDLE_NAME'].' '.$student['LAST_NAME'].' '.$student['NAME_SUFFIX'].'</div></DIV>';
echo'</td></tr>';
echo '<tr><td>'._('Email').'</td><td>:</td><td>'.TextInput($student['EMAIL'],'students[EMAIL]','','size=100 class=cell_medium maxlength=100').'</td></tr>';
I don't know how I'm supposed to edit it or where to add the jquery code.
Note: I already have the following options as I've asked this question before:
Option1 :
$('body').on('blur', '.firstname, .lastname', function(){
var fname = $.trim($('.firstname').val()),
lname = $.trim($('.lastname').val()),
email = $('#email'),
// Set your domain name here
prefix = '#example.com';
if( fname != "" && lname != "" )
email.val( fname + '.' + lname + prefix );
else if( fname == "" && lname == "" )
email.val("");
else
email.val( (fname != "" ? fname : lname) + prefix );
});
Option2:
$('#firstName', '#lastName').keyup(function() {
var domain = 'example.com';
var email = $('#firtName').val() + '.' + $('#lastName').val() + '#' + domain;
$('#email').val(email);
});
My Problem is that I don't know how to apply any of this in my code.
Yes you can do this
if you have fields like this
<input type="text" name="fn" value="" id="firstname" maxlength="30" />
<input type="text" name="ln" value="" id="lastname" maxlength="30" />
<input type="text" name="em" value="" id="email" maxlength="30" />
put the following script at the bottom of your html content
dont forget to add the jquery library
<script type="text/javascript">
$("#lastname").blur(function() { //blur event is called when the textbox lost focus
var vall = $("#firstname").val()+$("#lastname").val()+"#example.com";
$("#email").val(vall);
}) ;
</script>
comment for further changes...
var namehandler = function(){
var firstname = $('[name="students[FIRST_NAME]"]');
var lastname = $('[name="students[LAST_NAME]"]');
var email = $('[name="students[EMAIL]"]');
if (firstname.val() == '' || lastname.val() == ''){
email.val('');
return;
}
email.val(firstname.val() + '.' + lastname.val() + '#email.com');
};
$(document).ready(function(){
$('[name="students[LAST_NAME]"]').keyup(namehandler);
$('[name="students[FIRST_NAME]"]').keyup(namehandler);
});
Here's a link to the JSFiddle: http://jsfiddle.net/xw44gwvt/1/
This makes the email change instantly when the first or last name changes using the keyup event.
EDIT:
I changed the selector to get element by name. Maybe this will help, let me know if it works. If not, I'll see what i can do otherwise.
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.
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.