Validation of the text field for search problems - javascript

I have a search box that has a default value as "Search",i need to write some javascript that checks if the value in the search box is either "Search" or empty, then i should not sent the request and i need to display "Please enter a keyword"`
Here is the code
<div id="search">
<form action="/" style="" method="post" name="searchForm" id="searchForm" onSubmit="grabSearch();">
<img src="/images/bg_search_left.jpg" id="search_box_left" width="5" height="32" alt="" />
<input id="search_box" type="text" value="Search" onblur="if (this.value == '') {this.value = 'Search';}" onfocus="if (this.value == 'Search') {this.value = '';}"/>
<input type="image" id="search_arrow" src="/images/bg_search_right.jpg" width="34" height="32" />
<input type="hidden" name="_page" value="SEARCH" />
<input type="hidden" name="_action" value="SEARCH" />
<input type="hidden" name="searchTerm" value="" />
</form>
</div>
function grabSearch(){
var search=document.getElementById('search_box').value;
if(search="Search"||search=""){
document.getElementById('search_box').value="Please Enter a keyword"
}
search=encodeSearch(search);
document.forms['searchForm'].searchTerm.value = search;
}
On form submit i am checking it and displaying the message "Please Enter a keyword". Although the message is displayed in the text field but the request is sent(which i don't want to happen) and also on focus of the text field i want the message(please enter a keyword)to go way too

In addition to Jeaffrey's answer, you are not using the correct comparison operators. It should be:
if(search === "Search" || search === ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}
After that change, you need to return that value from your onSubmit -
<form action="www.google.com" style="" method="post" name="searchForm" id="searchForm" onsubmit="return grabSearch();">

Have you tried to return false?
if(search == "Search" || search == ""){
document.getElementById('search_box').value="Please Enter a keyword";
return false;
}

Related

Form gets submitted even if validation fails

I want the username and password to be admin & admin respectively so as to successfully submit the form. But the form gets submitted even if username and password to not match admin & admin.
function validateOnSubmit() {
console.log("Called!");
var isValid = true;
document.getElementById("alert").className = "";
if (document.getElementById("login-password").value.length <= 4) {
isValid = false;
document.getElementById("alert").className = "doWiggle";
setTimeout(function(){
document.getElementById("alert").className = document.getElementById("alert").className.replace('doWiggle', '');
}, 300);
}else
{
if(document.getElementById("login-password").value != "admin" && document.getElementById("username").value != "admin") {
alert("Wrong Password!");
isValid = false;
}
}
console.log(isValid);
return isValid;
}
HTML
<div class="container">
<form action="home.html" id="login-form" method="post" onsubmit="return validateOnSubmit()">
<p class="form-header">Sign In</p>
<span>Username</span>
<br/>
<input type="text" name="username" id="username" autocomplete="off" required/>
<br/>
<br/>
<span>Password</span>
<br/>
<input type="password" name="login-password" id="login-password" onkeyup="return validate()" required/>
<p id="alert">Password should more than 4 characters!</p>
<br/>
<br/>
<input type="checkbox" name="rememberMe" class="rememberMe" id="rememberMe"/>
<label for="rememberMe">Remember Me</label>
<br/>
<br/>
<input type="submit" id="submit" value="Sign In"/>
<br>
<br>
<div id="options">
Not registered ?
</div>
<input type="hidden" name="operation" value="login">
</form>
</div>
<script type="text/javascript" src="js/validate.js"></script>
</body>
The way you need to call the validateOnSubmit() is this way:
<form onsubmit="return validateOnSubmit();">
Notice the return on the onsubmit event. Best guess would you would have forgotten the return keyword, which is not the same and it submits the <form>.
I also see you are using className. It is better to replace it with Element.classList:
element.classList.add(); // Similar to adding class.
element.classList.remove(); // Similar to removing class.
Or if you wanna toggle it, you can use:
element.classList.toggle();
Logic
The logic you have used is wrong:
if (document.getElementById("login-password").value != "admin" && document.getElementById("username").value != "admin") {
The above logic will not work. Use the following:
if (document.getElementById("login-password").value != "admin" || document.getElementById("username").value != "admin") {
It should be || operator here. Currently if any one of the username or password is right, then the form submits, which is wrong.
You need to make sure that you have no js errors. Your js function can be ignored if that happens.
As said above, validateOnSubmit() must be called somehow. The propper way is:
<form onsubmit="return validateOnSubmit();">

HTML button onClick listener calling HTML form onSubmit javascript function

I am a novice in web development, I have created a simple html page. The page has two buttons, Submit and Display Data. The Submit button is supposed to post form data to a particular page after validating the form. This button is working fine. I am facing a problem with the Display Data button. The button is supposed to open a separate page and there should not be any kind of form validation. The page is getting open but the form is also getting validated.
The html page:
<html>
<head>
<script>
function validateForm()
{
var name=document.forms["myForm"]["name"].value;
var email=document.forms["myForm"]["email"].value;
var mobile=document.forms["myForm"]["mobile"].value;
var address=document.forms["myForm"]["address"].value;
var atpos=email.indexOf("#");
var dotpos=email.lastIndexOf(".");
if (name==null || name=="")
{
alert("Name must be filled out");
return false;
}
else if (atpos<1 || dotpos<atpos+2 || dotpos+2>=email.length)
{
alert("Not a valid e-mail address");
return false;
}
else if(isNaN(mobile)||mobile.indexOf(" ")!=-1)
{
alert("Enter numeric value")
return false;
}
else if (mobile.length != 10)
{
alert("Enter 10 digit mobile");
return false;
}
else if (mobile.charAt(0)=="0")
{
alert("Mobile no should not start with 0");
return false;
}
else if (address==null || address=="")
{
alert("Address must be filled out");
return false;
}
}
</script>
</head>
<body>
<h2>Employee Details Entry</h2>
<form name="myForm" action="insertDisplay.php" onSubmit="return validateForm()" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" value="Submit"> <button onClick="location.href = 'insertDisplay.php'">Display Data</button>
</form>
</body>
</html>
Where am I going wrong? Why is the form validation function getting called?
place
<button onClick="location.href = 'insertDisplay.php'">Display Data</button> this line out of the form...
give this button the type you want to behave it.
<button type="button" onClick="location.href = 'insertDisplay.php'">Display Data</button>
You can take the values out of the form, or you can use, <input type="button"/> tag. It will not submit your form and will work as you intended.
<input type="button" value="display data" onClick="location.href = 'a.php'">
I suppose you also want your datas to be passed to your PHP file after clicking your button ?
If you push the out of the form will not be sended and you'll have no datas.
In fact, you want both buttons to submit your form, but only the first one should validate it ?
If this is it you can do this :
<form name="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" name="typesubmit" value="Submit" onclick="return validateForm();" />
<input type="submit" name="typesubmit" value="Display Data" />
</form>
You'll be abled on your insert.php file to make difference between display and submit by checking $_POST['typesubmit'] value.
And if you want your "display" button to post your form on another php file, you can do this :
<form name="myForm" action="insert.php" method="post">
Name: <input type="text" name="name"><br/>
Email: <input type="text" name="email"><br/>
Mobile: <input type="text" name="mobile"><br/>
Address: <input type="text" name="address"><br/>
<input type="submit" value="Submit" onclick="return validateForm();" />
<input type="submit" value="Display Data" onclick="document.myForm.action='display.php';" />
</form>

Form alerts for multipe inputs

I have the following code, and need to get an alert that will specify which fields are empty or null, and return an alert for each empty or null field. I'm new to JavaScript and struggling a great deal with this. Can anyone give me some advice on this?
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<TITLE></TITLE>
<SCRIPT LANGUAGE="JavaScript">
<!--
function checkForm(form){
var len = form.length;
//create for loop
for (var i=0; i<len; i++){
if (form.elements[i].type=="text" || form.elements[i].type==null){
if (form.fax number.value=="" || form.fax number.type==null){
alert("Please fill out the fax number field");
}
}
}
}
function emailTest(emailText){
var email = emailText.value;
var emailPattern = /^.+#.+\..{2,}$/;
if (!(emailPattern.test(email))) {
alert("Please enter a valid email address.");
document.myForm[1].focus();
}
}
// -->
</SCRIPT>
</HEAD>
<BODY>
<H3>Assignment 2 Form</H3>
<HR>
<FORM NAME="myForm" METHOD="post"
ACTION="mailto:joeschmoe#blahblah.ca">
Name:<BR>
<INPUT TYPE="text" size="30" NAME="name"><br>
Email address:<BR>
<INPUT TYPE="text" size="30" NAME="email address" onBlur="emailTest(this);"><br>
Phone number:<BR>
<INPUT TYPE="text" size="30" NAME="phone number"><br>
Fax number:<BR>
<INPUT TYPE="text" size="30" NAME="fax number"><p>
<INPUT TYPE="submit" VALUE="Submit Data" onClick="return checkForm(this.form);">
<INPUT TYPE="reset" VALUE="Reset Form">
</FORM>
</BODY>
</HTML>
Ok...wow. I spent way too much time on this.
Your form should look like the following:
<FORM NAME="myForm" id="myForm">
<label for="name">Name:</label><br />
<INPUT TYPE="text" size="30" NAME="name" /><br />
<label for="email_address">Email address:</label><BR />
<INPUT TYPE="text" size="30" NAME="email_address" /><br />
<label for="phone_number">Phone number:</label><BR />
<INPUT TYPE="text" size="30" NAME="phone_number" /><br />
<label for="fax_number">Fax number:</label><BR />
<INPUT TYPE="text" size="30" NAME="fax_number" /><br />
<INPUT TYPE="button" VALUE="Submit Data" onClick="return checkForm()" />
<INPUT TYPE="reset" VALUE="Reset Form" />
</FORM>
Form Summary:
You should utilize labels for form elements
Never use spaces for the name attribute or any identifying attribute for that matter (name, class, id)
inputs should end with /> as should any tag without an end tag (<br /> too)
I pulled out the onBlur event and just added it as a piece of the overall validation process. No need to make it too complicated
I used a button input type instead of a submit input type. See why in the JavaScript
And then your JavaScript:
function checkForm() {
var valid = false; //Set a boolean variable that will be changed on each block
//of validation
if (document.myForm.fax_number.value === "") {
alert("Please fill out the fax number field");
}
if (document.myForm.email_address.value === "") {
alert("Email address is required");
} else {
valid = emailTest(document.myForm.email_address.value);
}
//all other checks within if statements
if (valid) {
document.myForm.action = "mailto:soandso#so.com";
document.myForm.submit();
}
}
function emailTest(emailText) {
var emailPattern = /^.+#.+\..{2,}$/;
var ret = false;
if (!(emailPattern.test(emailText))) {
alert("Please enter a valid email address.");
} else {
ret = true;
}
return ret;
}
Javascript Summary
In JavaScript interacting with HTML forms, forms are called as such: document.formName where formName is the string in the name="" attribute of the form tag or document.forms[i] where i is the numerical instance of the form on the page, i.e. the first form on the page is i = 0, thus it would be called as document.forms[0]
Check each input by name for a value with document.myForm.(elementName).value where elementName is the string from your <input>s name attribute.
Instead of using a submit, I used a regular button. When the "Submit Data" button is clicked in the form, it runs checkForm() which makes sure everything is valid
If everything is valid, it assigns an action to the form with document.myForm.action=youraction and then submits it via JavaScript with document.myForm.submit()
Notes
Don't use W3Schools to learn about anything ever.
Read more about forms here

Form Validation: when all forms are filled out properly my successful alert popup does not show

My Javascript code:
if (valid == false){
alert(errmsg);
return false;
}else {
var success = "Name: "+fname+" "+lname+"\n"+
"Email: "+email+"\n"+"Address: "+adr1+", "+adr2+","+
adr3+" "+zip;
alert(success);
}
all that pops up is a blank alert window.
any help or insight would be greatly appreciated.
I'm kinda new to this, let me know if you need clarifications
heres my html portion of the code
<form id="contactInfo" action="">
<p class="name">
<span class="nameHead">Name</span>
<br />
First:
<input type="text" name="fname" id="fname" />
Last:
<input type="text" name="lname" id="lname" />
</p>
<p>
Email:
<input type="text" name="email" id="email" size="55" />
<p class="address">
<span class="addressHead">Address</span>
<br />
Street:<input type="text" name="street" id="adr1" />
<br />
City: <input type="text" name="city" id="adr2"/>
<br />
State:<input type="text" name="state" id="adr3" size="2" maxlength="2"/>
<br />
ZIP Code: <input type="text" name="zipCode" id="zip" size="10" maxlength="10"/>
</p>
<p>
<input type="submit" value="Submit" onclick="return validate();" />
<input type="reset" value="Reset" />
</p>
</form>
if the user enters name, city, zip, and email wrong (searched for patterns) so my if statements look like this
if (adr1 == ''){
errmsg = errmsg + "Street address is blank\n";
valid = false;
focusA1.focus();
focusA1.select();
}else if(adr1S == -1){
errmsg = errmsg + "Street address should be in the form of digits followed by letters\n";
valid = false;
focusA1.focus();
focusA1.select();
}
if valid ends up being false at the end of the function the errmsg shows up with what is wrong and focuses on that portion of the form. One thing problem i did end up running into is that whenever the page loaded the form would automatically submit. would it have anything to do with this?
<body onload= "rotate()">
<img src="images/a.jpg" name="banner" class="banner" />
code for a rotating banner?
The way I have it set up is to show another alert for when all form fields are entered correctly and when i do enter them correctly no alert shows up
in your validation function try some thing like this
function validation()
{
var valid == true;
if(cond1)
{
alert(cond1fails);
valid=false;
}
if(cond2)
{
alert(cond2fails);
valid=false;
}
.... and so on on to all the conditions .....
// then in the last line
return valid;
}
try this it should simply work

How can I have a form where the text in the input disappears when clicked? (for feedburner form)

I've got the following "subscribe by e-mail" form:
<form style="border:1px solid #ccc;padding:3px;text-align:center;" action="http://feedburner.google.com/fb/a/mailverify" method="post" target="popupwindow" onsubmit="window.open('http://feedburner.google.com/fb/a/mailverify?uri=food101coil', 'popupwindow', 'scrollbars=yes,width=550,height=520');return true">
<p>enter e-mail:</p>
<p><input type="text" style="width:140px" name="email"/></p><input type="hidden" value="food101coil" name="uri"/><input type="hidden" name="loc" value="en_US"/><input type="submit" value="SEND" /></form>
I want to move the "enter e-mail" section inside the form part. So that when the user clicks on it, the text will disappear.
Could someone please help me with how to do that?
The following code will do what you want, but also maintain an email once entered..
HTML
<input id="email" type="text" style="width:140px" name="email" value="enter e-mail"/>
JavaScript
<script type="text/javascript">
var emailfield = document.getElementById('email');
emailfield.onfocus = function(){
if (this.value == 'enter e-mail') this.value = '';
}
emailfield.onblur= function(){
if (this.value == '') this.value = 'enter e-mail';
}
</script>
Live example: http://www.jsfiddle.net/YS2Xm/
<input type="text" name="email" onclick="this.value='';" value="enter e-mail" />
Not tested, should work though!

Categories

Resources