jQuery and input forms - javascript

I made this input form with Name and Text.
<form action="" method="post" class="main">
<label>Write a comment!</label><br>
<input placeholder="Name" class="form-text" name="user" type = "text" id = "user" autofocus size = "48"><br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>
and I added some jQuery for this form.
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
if (userCheck == '' || userCheck == NULL){
userBox.addClass("form-text-error");
console.log(userBox);
return false;
}
});
And now I'm here with this problem. I want the user to fill both fields in order to write a comment (name & text). For any empty fields I want to add class "form-text-error" . Everything works except for field with users name.
Any suggestions?

Use Length to get length of input then if return zero do addClass
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
if (commentCheck.length <= 0 || commentCheck == NULL) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
if (userCheck.length <= 0 || userCheck == NULL) {
userBox.addClass("form-text-error");
console.log(userBox);
return false;
}
});
.form-text-error {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" class="main">
<label>Write a comment!</label><br>
<input placeholder="Name" class="form-text" name="user" type="text" id="user" autofocus size="48"><br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br />
<input type="submit" class="form-submit" name="new_comment" value="Submit comment">
</form>
Also you can use submit function instead of click:
$(".form-submit").submit(function() {});
But i recommend you to use something like this:
$(".form-submit").click(function(e) {
e.preventDefault(); //remove this later
$('.form-text').each(function() {
if ($(this).val().length <= 0) {
$(this).addClass('form-text-error');
return false;
} else {
$(this).removeClass('form-text-error');
return true;
}
});
});

it is due to condition if return with false so it will check 1st condition and return back no further check.
need to make changes accordingly as below.
$(".form-submit").click(function() {
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var err = false;
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
err = true;
}
if (userCheck == '' || userCheck == NULL){
userBox.addClass("form-text-error");
console.log(userBox);
err = true;
}
if(err)
return false;
});

You are doing return false after comment
if(commentCheck == '' || commentCheck == NULL ) {
commentBox.addClass("form-text-error");
console.log(commentBox);
return false;
}
That's why it didn't get name field
You can use like this as like your requirement,
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var flag =0;
if(commentCheck == '' || commentCheck == NULL ) {
$("#comment").addClass("form-text-error");
console.log(commentBox);
flag = 1;
}
if (userCheck == '' || userCheck == NULL){
$("#user").addClass("form-text-error");
console.log(userBox);
flag = 1;
}
if(flag == 1)return false;

Use input type="button" and use this snippet that's tested and it works...
$("#comment").removeClass("form-text-error");
$("#user").removeClass("form-text-error");
var commentBox = $("#comment");
var userBox = $("#user");
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var flag =0;
var flag1 =0;
if(commentCheck == '' || commentCheck == null ) {
$("#comment").addClass("form-text-error");
console.log(commentBox);
flag = 1;
}
if (userCheck == '' || userCheck == null){
$("#user").addClass("form-text-error");
console.log(userBox);
flag1 = 1;
}
if(flag == 1 || flag1 == 1){return false;}
else{return true;}

You are returning false for both the validations.
Also, use .length === 0 || !box.
A common function would help.
Fixed
use e.preventDefault(); This would validate the username field as well and would not submit if empty.
var commentBox = $("#comment");
var userBox = $("#user");
function checkIfEmpty(box, check) {
if (check.length === 0 || !box) {
box.addClass("form-text-error");
console.log(box);
return true;
} else {
box.removeClass("form-text-error");
return false;
}
}
$(".form-submit").on('click', function(e) {
e.preventDefault();
var commentCheck = commentBox.val();
var userCheck = userBox.val();
var commentCall = checkIfEmpty(commentBox, commentCheck);
var userCall = checkIfEmpty(userBox, userCheck);
if(userCall === true && commentCall === true) {
return false;
}
});
.form-text-error {
background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" class="main">
<label>Write a comment!</label>
<br/>
<input placeholder="Name" class="form-text" name="user" type="text" id="user" autofocus size="48"/>
<br/>
<textarea class="form-text" name="comment" id="comment" placeholder="Text"></textarea>
<br/>
<input type="submit" class="form-submit" name="new_comment" value="Submit comment"/>
</form>

Related

JS - How to stop form submission while text is empty AND checkbox is not ticked?

This is my script so far. The aim is to not allow submission while the text boxes are empty,
var chk = document.getElementsByName('termsChkbx')[0];
var btn = document.getElementsByName("submit")[0];
var fname = document.forms["bookingForm"]["forename"].value;
var sname = document.forms["bookingForm"]["surname"].value;
var cname = document.forms["bookingForm"]["companyName"].value;
document.getElementsByName('termsChkbx')[0].onclick = function() {
textCol()
};
function textCol() {
if (chk.checked) {
document.getElementById("termsText").style.color = "black";
document.getElementById("termsText").style.fontWeight = "normal";
btn.disabled = false;
if (fname == null || fname == "", sname == null || sname == "") {
btn.disabled = true;
}
}
else {
document.getElementById("termsText").style.color = "red";
document.getElementById("termsText").style.fontWeight = "bold";
btn.disabled = true;
}
}
I know there is something wrong with the logic in the second if statement, but I cant figure out how I can allow the button to be pressed when the box is ticked, but not allow it when the fields are empty.
<p><input type="submit" name="submit" value="Book now!" disabled=""></p>
Heres the HTML for the button, which I am unable to change. Any help would be appreciated.
I don't think you want to use , in if (fname == null || fname == "", sname == null || sname == ""). You could simplify it:
var chk = document.getElementsByName('termsChkbx')[0];
var btn = document.getElementsByName("submit")[0];
var fname = document.forms["bookingForm"]["forename"];
var sname = document.forms["bookingForm"]["surname"];
function validate() {
if(fname.value == "" || sname.value == "" || !chk.checked) {
btn.disabled = true
} else {
btn.disabled = false
}
}
validate()
chk.addEventListener("click", validate)
fname.addEventListener("change", validate)
sname.addEventListener("change", validate)
<form name="bookingForm">
<input type="text" name="forename">
<input type="text" name="surname">
<input type="checkbox" name="termsChkbx">
<input type="submit" value="Submit" name="submit">
</form>

InnerHTML in multiple fiields and more than one error statements

I am having trouble trying to get the form to validate using the onblur handler.
What I am trying to do is to get the first and last name field to display an error message if the field is blank, if it’s less than 5 , more than 18 characters, or it the user enters a number.
I would like to be able to do this using only one function so I do not need to do this for seperate functions.
Eg:
function ValidateName(field) {
var field = field.value;
var output = document.getElementById("fnameError");
if (field == "")
{
output = "field can’t be blank.";
return false;
}
else
{
output = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the question.
function ValidateName(field) {
var output = document.getElementById("fnameError");
if (field.value == "")
{
output.innerHTML = "field can’t be blank.";
}
else
{
output.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName(this)">
<span id="fnameError"></span>
</form>
Your answer according to the the comment made on my answer.
function ValidateName() {
var outputF = document.getElementById("fnameError");
var outputL = document.getElementById("lnameError");
var outputB = document.getElementById("BothError");
var field1 = document.getElementById("Fname");
var field2 = document.getElementById("Lname");
if (field1.value == "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "No field can be left blank.";
outputL.innerHTML = "";
}
else if (field1.value !== "" && field2.value == "")
{
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "field can’t be blank.";
}
else if (field1.value == "" && field2.value !== "")
{
outputF.innerHTML = "field can’t be blank.";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
else {
outputF.innerHTML = "";
outputB.innerHTML = "";
outputL.innerHTML = "";
}
}
<form>
<input type="Text" id="Fname" onblur="ValidateName()">
<span id="fnameError"></span>
<br><br>
<input type="Text" id="Lname" onblur="ValidateName()">
<span id="lnameError"></span>
<br><br>
<span id="BothError"></span>
</form>
you can try this also
function validateform(){
var name=document.myform.name.value;
if (name==null || name==""){
alert("Name can't be blank");
return false;
}
else if(name.length < 5){
alert("name must be atleast 8 characters long");
return false;
}
else if(name.length <18){
alert("text must be more than 18 characters");
return false;
}
}
<form name="myform" method="post" action="" onsubmit="return validateform()" >
Name: <input type="text" name="name"><br/>
<input type="submit" value="register">
</form>

document.getElementById is not working for a form

I have some code like this:
HTML
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
<input type = "password" id = "currentPw" name = "currentPw" class="loginBlank" style = "width:300px;margin-top:0px;" placeholder="Current Password"/>
<input type = "password" id = "newPw" name = "newPw" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="New password"/>
<input type = "password" id = "newPwCheck" name = "newPwCheck" class="loginBlank" style = "width:300px;margin-top:10px;" placeholder="Retype new password"/>
<input type = "button" id = "submitBtn" onclick = "checkChangeForm()" class = "loginBlank" value = "Confirm" style = "width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
JavaScript
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
Supposing that by the time the button is pressed, the form would have been loaded, and when the variable is created by document.getElementById("changePwForm") again, it should be existing. However, it returned NULL. Why? What is wrong here?
Fiddle: https://jsfiddle.net/fL0z59o3/#&togetherjs=FAKVrL1jG3
Inline-events expect function to be in global-scope, not under the scope of window.onload
If you want to go on with window.onload, bind event using addEventListener or Element.onEVENT_NAME
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
document.getElementById('submitBtn').addEventListener('click',checkChangeForm);
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
Without window.onload
function checkChangeForm() {
var current = document.getElementById("currentPw").value;
var newPw = document.getElementById("newPw").value;
var newPwCheck = document.getElementById("newPwCheck").value;
if (current != "" && newPw != "" && newPwCheck != "") {
if (newPw == newPwCheck) {
if (newPw.length >= 8) {
alert("OK");
document.getElementById("changePwForm").submit();
} else {
alert("Passwords must be longer than 8 characters.");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("The password does not match!");
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("newPw").focus();
}
} else {
alert("No password entered");
document.getElementById("currentPw").value = "";
document.getElementById("newPw").value = "";
document.getElementById("newPwCheck").value = "";
document.getElementById("currentPw").focus();
}
}
<div id="inputs" style="width:300px;">
<form id="changePwForm" name="changePwForm" method="POST" action="me.php">
<input type="password" id="currentPw" name="currentPw" class="loginBlank" style="width:300px;margin-top:0px;" placeholder="Current Password" />
<input type="password" id="newPw" name="newPw" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="New password" />
<input type="password" id="newPwCheck" name="newPwCheck" class="loginBlank" style="width:300px;margin-top:10px;" placeholder="Retype new password" />
<input type="button" id="submitBtn" onclick="checkChangeForm()" class="loginBlank" value="Confirm" style="width:300px;margin-top:10px;font-size:16px;" />
</form>
</div>
include your script just near the end of the body tag, and see if it works.
Just found the problem... I nested the <form> element in another <form> element... Removing the outer one made it work.
Please move your script just near the end of the body tag
<body>
<div id = "inputs" style="width:300px;">
<form id = "changePwForm" name = "changePwForm" method = "POST" action = "me.php">
........
</form>
<script>
function checkChangeForm() {
.....
}
</script>
</div>
</body>

Check all elements in form with Javascript

I know javascript in the beginning level, but I have a problem.
I have 7 input elements in a form and I want all of them to be filled.
I came up with this idea but it looks disgusting.
Can someone help me how to check whether all form elements are filled or not?
function validateForm()
{
var x=document.forms["register"]["name"].value;
var y=document.forms["register"]["phone"].value;
var z=document.forms["register"]["compname"].value;
var q=document.forms["register"]["mail"].value;
var w=document.forms["register"]["compphone"].value;
var e=document.forms["register"]["adres"].value;
var r=document.forms["register"]["zip"].value;
if (x==null || x=="" || y==null || y=="" || z==null
|| z=="" || q==null || q=="" || w==null || w=="" || e==null || e==""
|| r==null || r=="")
{
alert("Please fill all the inputs");
return false;
}
}
</script>
This is the simple and dirty way.
A better way is to update a validation message that the fields are required.
function validateForm()
{
var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]
var i, l = fields.length;
var fieldname;
for (i = 0; i < l; i++) {
fieldname = fields[i];
if (document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}
With some simple vanilla JS, you can handle this in a lot more simplified way:
JavaScript
function validateForm(){
var form = document.getElementById("register"), inputs = form.getElementsByTagName("input"), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(!input.value) {
flag = false;
input.focus();
alert("Please fill all the inputs");
break;
}
}
return(flag);
}
Then make sure you return the function within your form, either inline (bad practice):
<form name="register" id="register" method="post" action="path/to/handler.php" onsubmit="return validateForm();">
Or in a more unobtrusive way:
window.onload = function(){
var form = document.getElementById("register");
form.onsubmit = function(){
var inputs = form.getElementsByTagName("input"), input = null, flag = true;
for(var i = 0, len = inputs.length; i < len; i++) {
input = inputs[i];
if(!input.value) {
flag = false;
input.focus();
alert("Please fill all the inputs");
break;
}
}
return(flag);
};
};
<html>
<head>
<title> Event Program</title>
<script>
function validateForm() {
var fields = ["name, phone", "compname", "mail", "compphone", "adres", "zip"]
var i, l = fields.length;
var fieldname;
for(i = 0; i < l; i++) {
fieldname = fields[i];
if(document.forms["register"][fieldname].value === "") {
alert(fieldname + " can not be empty");
return false;
}
}
return true;
}
var _validFileExtensions = [".jpg", ".jpeg", ".bmp", ".gif", ".png"];
var fields = {
"eventName": "Event Name",
"eventDate": "Event Date",
"eventPlace": "Event Place"
}
function Validate(oForm) {
var arrInputs = oForm.getElementsByTagName("input");
for(var i = 0; i < arrInputs.length; i++) {
var oInput = arrInputs[i];
if(oInput.type == "text" && oInput.value == "") {
alert(fields[oInput.name] + " cannot be empty");
return false;
}
if(oInput.type == "file") {
var sFileName = oInput.value;
if(sFileName.length > 0) {
var blnValid = false;
for(var j = 0; j < _validFileExtensions.length; j++) {
var sCurExtension = _validFileExtensions[j];
alert(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase())
if(sFileName.substr(sFileName.length - sCurExtension.length, sCurExtension.length).toLowerCase() == sCurExtension.toLowerCase()) {
blnValid = true;
break;
}
}
if(!blnValid) {
alert("Sorry, " + sFileName + " is invalid, allowed extensions are: " + _validFileExtensions.join(", "));
return false;
}
}
}
}
return true;
}
</script>
</head>
<body>
<div align="center">
<h3>Event Management</h3>
<form onsubmit="return Validate(this);" id='eventForm' name='eventForm' method='POST' enctype='multipart/form-data' action='saveEvent.php'>
<table>
<tr>
<td>Event Name</td>
<td>
<input type="text" name="eventName">
</td>
</tr>
<tr>
<td>Event Date</td>
<td>
<input type="text" name="eventDate" id='datepicker'>
</td>
</tr>
<tr>
<td>Event place</td>
<td>
<input type="text" name="eventPlace">
</td>
</tr>
<tr>
<td>Upload Image</td>
<td>
<input type="file" name="my file" />
<br />
</td>
</tr>
<tr>
<td>About Events</td>
<td>
<textarea></textarea>
</td>
</tr>
<tr>
<td colspan=2 align=center>
<input type="submit" value="Submit" />
<input type="button" name="clear" value="Clear" />
</td>
</tr>
</table>
</form>
</div>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<script>
$(function () {
$("#datepicker").datepicker({
dateFormat: "dd/mm/yy",
changeMonth: true,
changeYear: true
}).datepicker("setDate", new Date());
});
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script>
function validateForm() {
let x = document.forms["myForm"]["fname"].value;
if (x == "") {
document.getElementById('namecheck').innerHTML="Name must be filled out";
return false;
}
else{
document.getElementById('namecheck').innerHTML="";
}
let y = document.forms["myForm"]['age'].value;
if (y == "") {
document.getElementById('agecheck').innerHTML="Age must be filled out";
return false;
}
else{
document.getElementById('namecheck').innerHTML="";
}
let z = document.forms["myForm"]['phone'].value;
if (z == "") {
document.getElementById('phonecheck').innerHTML="Phone must be filled out";
return false;
}
else{
document.getElementById('phone').innerHTML="";
}
}
</script>
</head>
<body>
<h2>JavaScript Validation</h2>
<form name="myForm" action="/action_page.php" onsubmit="return validateForm()" method="post">
Name: <input type="text" name="fname">
<p id='namecheck' style="color:red"></p>
Age: <input type="text" name="age">
<p id='agecheck' style="color:red"></p>
Phone: <input type="text" name="phone">
<p id='phonecheck' style="color:red"></p>
<input type="submit" value="Submit">
</form>
</body>
</html>
You can use this easy method to validate all fields of form.
You could just do this:
//Declare variables
var 1, 2, 3, 4, 5, 6, 7;
1 = document.getElementById("Field Id");
2 = document.getElementById("Field Id");
3 = document.getElementById("Field Id");
4 = document.getElementById("Field Id"); //Define variable values
5 = document.getElementById("Field Id");
6 = document.getElementById("Field Id");
7 = document.getElementById("Field Id");
//Check if any of the fields are empty
If (1 == "" || 2 == "" || 3 == "" || 4 == "" || 5 == "" || 6 == "" || 7 == "") {
alert("One or more fields are empty!");
//Other code
}
I used this for my own form and it works fine while not taking up to much space or looking too "ugly". It works for all field elements and checks the value entered.

Return an empty field name from validation form

http://jsfiddle.net/3vHxF/ Here is what I tried
And my html code is :
<form id="commentForm" style="width:200px;" name="MYFORM" action="#">
<label>
<strong>Enquiry Form </strong>
</label>
<label>Name</label>
<input id="name" type="text" size="30" name="name">
<label>Phone No</label>
<input id="phone" type="text" size="30" name="phone">
<label>Email</label>
<input id="email" type="text"size="30" name="email">
<label>Message</label><br>
<textarea id="message" name="message"></textarea>
<input id="Send" type="submit" value="Send" onclick="send()">
</form>
Javascript is :
var name=getElementById('name');
var phone=getElementById('phone');
var email=getElementById('email');
var mess=getElementById('message');
function send(){
if(name==null&&phone==null&&email==null&&mess==null)
alert('field is empty');
}
I want to alert the field which is empty, and at the same time I want to write it simply. Please don't suggest any plug-ins.
Remove the click handler from the button and put a submit handler on the form:
<form id="commentForm" onsubmit="return validat(this);" ... >
Now you can do a simple validation:
function validate(form) {
var control;
var isValid = true;
for (var i=0, iLen=form.elements.length; i<iLen; i++) {
control = form.elements[i];
if (control.value == '') {
alert('Field ' + control.name + ' is empty');
isValid = false;
}
}
return isValid; // false cancels submit
}
That is a very minimal validation script, but it's a start.
Incidentally, since your form controls have names (which are required to be successful), they don't need ids.
Your problems:
You are testing HTMLInputElement objects and not the values they hold (so get the value)
You are comparing strings to null (compare to an empty string)
Your failure condition is based on all of them failing instead of any of them failing (use or not and)
Such:
if(name.value === "" || phone.value === "" || email.value === "" || mess.value === "")
alert('field is empty');
}
To determine which one is empty, you need to test them one at a time instead of in a single if statement with ||s.
Not a clean approach. But try developing the below code.
var name=document.getElementById('name').value;
var phone=document.getElementById('phone').value;
var email=document.getElementById('email').value;
var mess=document.getElementById('message').value;
function send(){
if(isEmpty(name, 'name') || isEmpty(phone, 'phone') || isEmpty(email, 'email') || isEmpty(mess, 'message')) {
return false;
}
return true;
}
function isEmpty(val, fld) {
if(val && val != null) {
return true;
}
alert(fld +" is Empty");
return false;
}
change
var name=getElementById('name');
var phone=getElementById('phone');
var email=getElementById('email');
var mess=getElementById('message');
to
var name=document.getElementById('name').value;
var phone=document.getElementById('phone').value;
var email=document.getElementById('email').value;
var mess=document.getElementById('message').value;
and then use
if(name.value === "" || phone.value === "" || email.value === "" || mess.value === "")
alert('field is empty');
}
You could use the following jQuery:
$(":text,textarea").each(function() {
$(this).css("outline", $(this).val() ? "1px solid red" : "none");
});
Sorry, I thought "no plugins" meant "no jQuery plugins." (You would call jQuery a library or dependency, not a "plugin")
This is a mostly untested non-jQuery version:
function highlightMissingInputs() {
for (var formIndex = 0; formIndex < document.forms.length; formIndex++) {
var form = document.forms[formIndex];
for (var inputIndex = 0; inputIndex < form.length; inputIndex++) {
var input = form[inputIndex];
switch (input.tagName) {
case "INPUT":
var typeAttribute = input.attributes.type;
if (typeAttribute) {
var type = (typeAttribute.value || "").toLowerCase();
switch (type) {
case undefined:
case "":
case "text":
case "email":
case "tel":
case "email":
case "search":
break;
default:
continue;
}
}
break;
case "TEXTAREA":
break;
default:
continue;
}
input.style.outline = input.value ? "none" : "1px solid red";
}
}
}

Categories

Resources