javascript if text box element is blank do different action - javascript

Trying to get this search form to do different searches but if the search box is empty, I want it to default to a different page. This is with the first else if. Even with the text box empty it keeps defaulting to the first action.
<script type="text/javascript">
function changeAction() {
if(document.getElementById('searchOption').value == "title" && document.getElementById('searchText').value!=null) {
document.getElementById('searchForm').action = 'catalog.com=0&term=' + escape(document.getElementById('searchText').value);
}
**else if(document.getElementById('searchOption').value == "title" && document.getElementById('searchText').value===null) {
document.action = 'differentPage.com'
}**
else if(document.getElementById('searchOption').value == "keyword") {
document.getElementById('searchForm').action = 'catalog.com?keyword=' + escape(document.getElementById('searchText').value);
}
else{
document.getElementById('searchForm').action = "mysite.com/searchResults.html";
$('#searchForm').attr('method', 'get');
$('#searchText').attr('name', 'q');
}
}
</script>
<form id="searchForm" name=search method=post>
<div class="subscribe">
<div class="text">
<input name="term" type="text" id="searchText"/>
</div>
<select id="searchOption" name="searchOption" title="search">
<option name="index" value="title" selected="selected">TITLE IN CATALOG</option>
<option name="index" value="keyword" type="hidden">CATALOG KEYWORD</option>
<option name="nothing" value="googleSearch" type="hidden">LIBRARY WEBSITE</option>
</select>
<!-- for google search appliance -->
<input value="slco_pub" name="client" type="hidden">
<input value="slco_pub" name="proxystylesheet" type="hidden">
<input value="xml_no_dtd" name="output" type="hidden">
<input value="mainSite" name="site" type="hidden">
<!-- end of necessary for google search appliance -->
<!-- for ILS -->
<INPUT name=menu value=search type=hidden>
<INPUT name=aspect value=basic_search type=hidden>
<INPUT name=profile value=maincentral type=hidden>
<!-- Left from old <INPUT name=index value=".TW" type=hidden> -->
<INPUT name=index value="PALLTI" type=hidden>
<!-- end of necessary for google search appliance-->
<!--Button Graphic-->
<input type="image" src="/sebin/m/p/btn-search.gif" alt="search button" onClick="changeAction();" />
</div>
</form>

document.getElementById('searchText').value!=null is using loose comparison, so it will be true if the value is null or undefined. In this case, it will always be a string. What you want to test is whether it is a non-empty string, like so:
var option = document.getElementById('searchOption').value,
text = document.getElementById('searchText').value,
form = document.getElementById('searchForm');
if (option === "title" && text.length > 0) {
form.action = 'catalog.com=0&term=' + escape(text);
}
else if (option === "title" && text.length === 0) {
form.action = 'differentPage.com'
}
else if (option === "keyword") {
form.action = 'catalog.com?keyword=' + escape(text);
}
else {
form.action = "mysite.com/searchResults.html";
$('#searchForm').attr('method', 'get');
$('#searchText').attr('name', 'q');
}
Note that I've used strict comparison.

Related

I need to add a message box and e-mail textbox and display everything in my form in the msgresults tag

I need to add a message box and e-mail textbox and display everything in my form in the 'msgresults' tag.
I need to add a Message box and and e-mail text box. Then I need all information to be shown within the MsgResults tag. The radioboxes already are shown this way.
function validateForm(){
var name = document.getElementById("name").value;
var age = document.getElementById("age").value;
if (name == "" || name == null){
resultsMsg("We need your name please");
}else{
if(age == "" || name == null || isNaN(age)){
resultsMsg("Please enter a number for your age");
}else{
if(!getSkill()){
resultsMsg("Please select the type of problem you are having.");
}else{
resultsMsg("Type of Problem: " + getSkill());
}//end else
}// end function
}
}
function getSkill(){
var isChecked = false;
var theSelection;
var skills = document.getElementsByName('skillset');
for (var i=0; i < skills.length; i++){
if(skills[i].checked){
isChecked = true;
theSelection = skills[i].value;
break;
}
}
if(isChecked){
return theSelection;
}else{
return false;
} // end else
} // end function
function resultsMsg(s){
var resultsBox = document.getElementById("results");
resultsBox.innerHTML=s;
} // end function
<form name="form1" id="form1" action="" method="post">
<label>Full Name:
<input type="text" id="name" name="name">
</label>
<br> <!-- new line here -->
<label>Your Age:
<input type="text" id="age" name="age">
</label>
<br> <!-- new line here -->
<input type="radio" name="skillset" value="Technical Issues">Technical Issues</br>
<input type="radio" name="skillset" value="Recovery Issues">Recovery Issues</br>
<input type="radio" name="skillset" value="Hardware Issues">Hardware Issues</br>
<input type="radio" name="skillset" value="Software Issues">Software Issues</br>
<input type="radio" name="skillset" value="Software Crashes">Software Crashes</br>
<input type="radio" name="skillset" value="Hardware Malfunctions">Hardware Malfunctions</br>
<input type="radio" name="skillset" value="General Problems">General Problems</br>
<input type="button" value="Submit" onClick="validateForm();"> <input type="reset" value="Clear Form">
</form>
<div id="results"></div>
If I understand your goal correctly, you want to add the given name and age to the result-div, on top of the 'Type of Problem' that is already show. That can be easily achieved by adding the correct variables to the last else-loop in your validateForm function. Something among the following should probably work:
resultsMsg("Name: "+name+ "<br>Age: " +age+ "<br>Type of Problem: " + getSkill());

Function that will only push value of most recent inputs

I have 3 groups of inputs, in chronological order (manufacturer info, repair info, test info). When the user hits the "confirm button", I want an if statement to iterate through each input, compare if (input.val() !== ""), and then make sure it is the most recent data (ie. repair info will supercede mfg info) before pushing that value to the #asreceived fields.
I have manually done an if statement for each set of inputs to iterate through, however I would have to add to the function if I wanted to enter more fields.
This is what I have currently:
$("#model-received").val(function() {
if ($("#model-test").val() != "") {
return $("#model-testonly").val();
} else if ($("#model-repair").val() != "") {
return $("#model-repair").val();
} else {
return $("#model-initial").val();
}
});
I have used this code for each set of inputs (roughly 50)
I have tried to compare groups using the .each(), but I am stuck here.
let $inputMfg = $("#manufacturers-tag").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-initial") > -1) {
return
}
});
let $inputRep = $("#repairtag-old").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-repair") > -1) {
return
}
});
let $inputTO = $("#testonlytag-old").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-testonly") > -1) {
return
}
});
let $inputAsRec = $("#asreceived").find("input , select").each(function() {
if ($(this).attr("name").indexOf("-received") > -1) {
return
}
});
$("#asreceived"),$("#testonlytag-old"),$("#repairtag-old"),$("#manufacturers-tag") are all the same HTML, minus the name suffix on each input ("-initial")
HTML
<div id="repairtag-old" hidden>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Company: </label>
<input class="entry-input" type="text" name="company-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Date: </label>
<input class="entry-date" type="date" name="date-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">VR Stamp: </label>
<select class="entry-select" id="vrstamp-old" name="vrstamp-old">
<option></option>
<option>Yes</option>
<option>No</option>
</select>
<label class="entry-bylabel">VR: </label>
<input class="entry-input" type="text" name="vrnumber-old">
</div>
</div>
<div class="entry-col2">
<div class="entry-line">
<label class="entry-label">Job Number: </label>
<input class="entry-input" type="text" name="jobnumber-repair">
</div>
</div>
<div class="entry-col2">
<div class="entry-line">
<label class="entry-label">Model Number: </label>
<input class="entry-input" id="model-repair" type="text" name="model-repair">
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Set Pressure: </label>
<input class="entry-input" id="setpressure-repair" type="text" name="setpressure-repair">
<select class="entry-select" name="setunit-repair">
<option>psig</option>
</select>
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Cold Test Pressure: </label>
<input class="entry-input" type="text" name="coldpressure-repair">
<select class="entry-select" name="coldunit-repair">
<option>psig</option>
</select>
</div>
</div>
<div class="entry-col3">
<div class="entry-line">
<label class="entry-label">Capacity: </label>
<input class="entry-input" type="text" name="capacity-repair">
<select class="entry-select" name="capacityunit-repair">
<option>scfm</option>
</select>
</div>
</div>
<br>
</div>
The final result should push the value of the most important value (test only 1st, repair 2nd, mfg 3rd). If the (input.val === ""), it should use the older values.
---UPDATED---
I figured it out. Code snippet below. Thank you for the responses, I was a little intimated in trying to implement them (I am new at coding). However, Mark Meyer's response got me on the right track. This works exactly as intended.
$("#copybtn-received").click(function(i) {
$("#asreceived").find("input, select").each(function() {
let $output = $(this).attr("name").split("-received")[0];
let $inputTO = $("#testonlytag-old").find("[name^=" + $output + "]");
let $inputRep = $("#repairtag-old").find("[name^=" + $output + "]");
let $inputMfg = $("#manufacturers-tag").find("[name^=" + $output + "]");
if ($inputTO.val() !== "") {
$(this).val($inputTO.val());
} else if ($inputRep.val() !== "") {
$(this).val($inputRep.val());
} else if ($inputMfg.val() !== "") {
$(this).val($inputMfg.val());
} else {
$(this).val("");
}
});
});
You could put your values in an array that is in the order of precedence you want then use find() which returns the first value found. In the find callback just return whether the value is truth, which "" isn't. This will allow you to decide arbitrary orders without all the if/else statements.
Here's a simplified example. It will log the highest value filled in.
function getBest(){
/* values in the order values will be found */
let values = [
document.getElementById("one").value,
document.getElementById("two").value,
document.getElementById("three").value,
document.getElementById("four").value
]
/* find the first truthy value */
let best = values.find(val => val)
console.log(best)
}
<input id="one" type ="text"><br />
<input id="two" type ="text"><br />
<input id="three" type ="text"><br />
<input id="four" type ="text"><br />
<button onclick="getBest()">Go</button>
I'm not sure I understand the question correctly, so this is a bit of a guess. Perhaps something like this would do?:
const findFirst = (ids, idx = ids.find(id => $(`#${id}`).val() !== '')) =>
idx > -1 ? $(`#${id}`).val() : 'not found'
$("#model-received").val(findFirst(
['model-testonly', 'model-repair', 'model-initial']
))
You can then update the list by simply appending to that array. And if the 'model-' prefix is universal, you can include that in the function and only pass ['testonly', 'repair', 'initial'] in the call.
I don't know if you have a better default than the 'not found' here.

error message in the form validation is not showing as expected

I am working on angularjs and bootstrap application. I'm trying to validate the simple form, when user click on submit button all the fields in the from should have a value.
Please find the demo : https://plnkr.co/edit/aHtODbTTFZfpIRO3BWhf?p=preview
In the demo above, when user click on submit button with out selecting the checkbox , an error message is shown 'Please Select the Color..' , after the error message is shown select the checkbox and click on submit button still the error message is displayed. Any inputs on this?
html code:
<form name="myForm" ng-controller="ExampleController">
<div>Select Color : </div>
<label name="color" ng-repeat="color in colorNames" class="checkbox-inline">
<input ng-required="selectedColor.length === 0" oninvalid="this.setCustomValidity('Please select the color..')" type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> <!--<input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}-->
{{color}} <br> </label>
<div class="">
<div style="color: black;">Username : </div>
<input type="text" name="user" value="" required>
<div ng-show="myForm.$submitted || myForm.user.$touched">
<p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
</form>
First
I have declared an array for all of the checkbox value:
$scope.selectedColor = [false,false,false];
Second
I added a method for check box validation check:
$scope.someSelected = function () {
for(var i = 0; i < $scope.selectedColor.length; i++) {
if($scope.selectedColor[i]) return true;
}
return false;
};
Third
I use ng-model and update the HTML code, ng-model is used for two-way data binding, and change to bind value will reflected in view and controller:
<input ng-required="!someSelected()" ng-model = "selectedColor[$index]" type="checkbox" name="color" value="{{color}}">
Forth
The user input box also do not have the ng-model so the change in view not be updated in controller. To solve this ng-model is added.
<input type="text" ng-model = "user" name ="user" value="" required>
Fifth
Updated the submit form validation:
$scope.submitForm = function(){
if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) {
alert("all fields are entered");
}else{
}
}
Thats all!
Please check the working code snippet:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Example - example-checkbox-input-directive-production</title>
<script src="//code.angularjs.org/snapshot/angular.min.js"></script>
</head>
<body ng-app="checkboxExample">
<script>
angular.module('checkboxExample', [])
.controller('ExampleController', ['$scope', function($scope) {
$scope.colorNames = ['RED', 'BLUE', 'BLACK'];
$scope.selectedColor = [false,false,false];
$scope.userSelection = function userSelection(team) {
var idx = $scope.selectedColor.indexOf(team);
if (idx > -1) {
$scope.selectedColor.splice(idx, 1);
}
else {
$scope.selectedColor.push(team);
}
};
$scope.submitForm = function(){
if ($scope.someSelected() && $scope.user != "" && $scope.user != undefined) {
alert("all fields are entered");
}else{
}
}
$scope.someSelected = function () {
for(var i = 0; i < $scope.selectedColor.length; i++) {
if($scope.selectedColor[i]) return true;
}
return false;
};
}]);
</script>
<form name="myForm" ng-controller="ExampleController">
<div>Select Color : </div>
<label name="color" ng-repeat="color in colorNames" class="checkbox-inline">
<input ng-required="!someSelected()" ng-model = "selectedColor[$index]" type="checkbox" name="color" value="{{color}}"> <!--<input type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)"> {{color}}-->
{{color}} <br> </label>
<div class="">
<div style="color: black;">Username : </div>
<input type="text" ng-model = "user" name ="user" value="" required>
<div ng-show="myForm.$submitted || myForm.user.$touched">
<p class="error-mesg" ng-show="myForm.user.$error.required">The Username is required</p>
</div>
</div>
<button type="submit" class="btn btn-primary" ng-click="submitForm(myForm)">Submit</button>
</form>
</body>
</html>
<!--
Copyright 2018 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
Solution is to update your (1) input field for colors, (2) input field for user and (3) submitForm method
<input ng-required="selectedColor.length === 0" onchange="this.setCustomValidity(!validity.valueMissing && '')" oninvalid="this.setCustomValidity(validity.valueMissing ? 'Please select the color..' : '')"type="checkbox" name="color" value="{{color}}" ng-checked="selectedColor.indexOf(color) > -1" ng-click="userSelection(color)">
<input type="text" name="user" value="" ng-model="user" required>
$scope.submitForm = function(form){
if ($scope.selectedColor.length > 0 && $scope.user != "") {
console.log('fields are all entered');
} else{
}
}
(1) You need to set the false condition to handle the checkbox when it is selected.
(2) For your user input field, you need to set ng-model=user to link the $scope.user object to the input.
(3) For the submitForm method, you want to know that the selectedColor array has at least one item, and that user is not empty.
As an ending point, please format your code using proper linting and indentation. Otherwise, it is difficult to read at first glance.

How to disable button until input field has a value using AngularJS

I know nothing about Angular but I was asked to create a validation for the new google map input. All I want to do is have the #lugar_continuar button stay disabled until the input #ciudad is filled in, but the button isn't disabled for some reason.
index.php, input to validate
<div class="">
<input id="ciudad" name="ciudad" class="ciudad" type="text"
placeholder="Ciudad" value="" required ng-model="ciudadSet">
<div id="map"></div>
<input type="hidden" id="distance" size="31" value="31">
</div>
Input type button that should stay disabled
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && ciudadSet" ng-click="from_precio = true" >
Using ng-model doesn't work. I also tried with JS, in main.js:
var ReservasApp = angular.module('Reservas',['rzModule']);
ReservasApp.controller('ReservasController',function($scope){
$scope.ciudad = "";
$scope.validacionCiudad = function() {
var disabled = false;
if( $scope.ciudad != null && $scope.ciudad != "" )
{
disabled = false;
}
else
{
disabled = true;
}
}
}
index.php
<input id="lugar_continuar" name="lugar_continuar" type="button" onClick="_gaq.push(['_trackEvent', 'Reserva', 'Continuar', 'preciohome'])" value="Continuar" ng-disabled="validacion2() && validacionCiudad()" ng-click="from_precio = true" >
I also tried using only JS:
var validacionCiudad = function() {
var ciudad = document.getElementById('ciudad');
var btn = document.getElementById('lugar_continuar');
if (ciudad.value == "") {
btn.setAttribute("disabled", "disabled");
} else {
btn.removeAttribute("disabled");
}
}
validacionCiudad();
I have tried many ways to achieve this but nothing is working!
you can try this: ng-disabled = "ciudadSet == ''", since ng-disabled is valid when the expression equals true. If you must call function validacionCiudad to judge this, you have to return bool value in your function. May this will help.
Change $scope.ciudad ="" to $scope.ciudad = undefined;
change your ng-model to:
ng-model="ciudad"
and your ng-disabled to:
ng-disabled="!ciudad"
that shall work
You can validate it like this.
<div ng-controller="MyCtrl">
<form name="userForm" ng-submit="submitForm(userForm.$valid)" novalidate>
<input name="name" ng-model="name" type="text" required >
<br>
<button type="submit" ng-disabled="userForm.$invalid" >Enviar</button>
</form>
</div>
https://jsfiddle.net/ivanm07/y2t88817/

Basic JavaScript validation not working

I'm trying to make a simple form with JavaScript validation. It has four fields: title, email address, rating and comments. As far as I know, the code I have here should work to validate the form and I should not be allowed to submit it but whenever I press the submit button none of the prompts appear and the browser submits the form. Could someone let me know where I am going wrong please? I'd imagine there is a simple solution or something I am forgetting but I'm pretty new to this so apologies if it's something very obvious.
The HTML and JavaScript code is:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e=document.forms["review"]["Title"].value;
var s=document.forms["review"]["Email"].value;
var t=document.forms["review"]["Rating"].value;
var c=document.forms["review"]["Comments"].value;
var atsym=s.indexOf("#");
var dotsym=s.lastindexOf(".");
if (e==null || e=="")
{
document.getElementById("valAlert").innerHTML="Please Enter a Title";
return false;
}
else if (s==null || s=="" || atsym<1 || dotsym<atsym+2 || dotsym+2>=s.length)
{
document.getElementById("valAlert").innerHTML="That is not a valid email address!";
return false;
}
else if (t=="0")
{
document.getElementById("valAlert").innerHTML="You must enter a rating";
return false;
}
else if (c==null || c=="")
{
document.getElementById("valAlert").innerHTML="You need to enter some kind of comment.";
return false;
}
else
{
alert ("Your review of " + t + "has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title">
</br>
</br>
Enter Email Address:
<input type="text" name="Email">
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit"/>
</fieldset>
</form>
</body>
please make a null value check before doing the operations like below
var dotsym=s.lastindexOf(".");
Add the null check for variable 's'.Please check the function naming convention below
obj.lastindexOf(); TO obj.lastIndexOf(".");
You’ve said there were no errors, but you might just be missing them when the form submits and the console is cleared.
If you’re using Chrome/Chromium, you can enable breaking on exceptions in the Sources tab of the developer tools (the icon on the far right should be purple or blue):
In Firefox, it’s in the Debugger Options menu:
As #Rajesh says, the casing you have on lastindexOf is wrong; it should be lastIndexOf.
Now, let’s fix everything else up, starting with formatting:
<html>
<head>
<script type="text/javascript">
function validateForm()
{
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
var atsym = s.indexOf("#");
var dotsym = s.lastIndexOf(".");
if (e == null || e == "")
{
document.getElementById("valAlert").innerHTML = "Please Enter a Title";
return false;
}
else if (s == null || s == "" || atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length)
{
document.getElementById("valAlert").innerHTML = "That is not a valid email address!";
return false;
}
else if (t == "0")
{
document.getElementById("valAlert").innerHTML = "You must enter a rating";
return false;
}
else if (c == null || c == "")
{
document.getElementById("valAlert").innerHTML = "You need to enter some kind of comment.";
return false;
}
else
{
alert("Your review of " + t + " has been submitted!");
}
}
</script>
</head>
<body>
<div id="valAlert"></div>
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
</br>
</br>
Enter Email Address:
<input type="text" name="Email" />
</br>
</br>
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</br>
</br>
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
</br>
</br>
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
</body>
You’re missing a DTD and a closing </html>, so add those:
<!DOCTYPE html>
<html>
…
</html>
Next, </br> doesn’t exist. It’s <br />.
<form name="review" onsubmit="return validateForm()">
<fieldset>
Enter Title:
<input type="text" name="Title" />
<br />
<br />
Enter Email Address:
<input type="text" name="Email" />
<br />
<br />
Please Enter Your Rating:
<select name="Rating">
<option value="0">(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
<br />
<br />
<textarea name="Comments" rows="8" colspan="40">Comments:</textarea>
</fieldset>
<br />
<br />
<fieldset>
<input class="button" type="submit" value="Submit" />
</fieldset>
</form>
Here:
var e = document.forms["review"]["Title"].value;
var s = document.forms["review"]["Email"].value;
var t = document.forms["review"]["Rating"].value;
var c = document.forms["review"]["Comments"].value;
the properties are valid JavaScript identifiers, so you can write them with the dot syntax:
var e = document.forms.review.Title.value;
var s = document.forms.review.Email.value;
var t = document.forms.review.Rating.value;
var c = document.forms.review.Comments.value;
You should probably give them clearer names, too; I think you used the wrong one in that last alert, and this will help:
var title = document.forms.review.Title.value;
var email = document.forms.review.Email.value;
var rating = document.forms.review.Rating.value;
var comments = document.forms.review.Comments.value;
Next, you don’t need elses when you’re returning from the if case no matter what, so you can drop those. The values of text inputs can never be null, so stop checking for those. It’ll also save some typing (or copying) to keep valAlert as a variable.
var atsym = email.indexOf("#");
var dotsym = email.lastindexOf(".");
var valAlert = document.getElementById("valAlert");
if (title === "") {
valAlert.innerHTML = "Please Enter a Title";
return false;
}
if (atsym < 1 || dotsym < atsym + 2 || dotsym + 2 >= s.length) {
valAlert.innerHTML = "That is not a valid email address!";
return false;
}
if (rating == "0") {
valAlert.innerHTML = "You must enter a rating";
return false;
}
if (comments == "") {
valAlert.innerHTML = "You need to enter some kind of comment.";
return false;
}
alert("Your review of " + title + " has been submitted!");
Voilà! But wait; there’s more. The best things in life web development don’t need JavaScript, and this is no exception.
<!DOCTYPE html>
<html>
<head>
<title>HTML5 validation</title>
</head>
<body>
<form>
<fieldset>
<label>
Enter title:
<input type="text" name="title" required />
</label>
<label>
Enter e-mail address:
<input type="email" name="email" required />
</label>
<label>
Please enter your rating:
<select name="rating" required>
<option>(Please select a rating)</option>
<option value="1S">1 Star</option>
<option value="2S">2 Stars</option>
<option value="3S">3 Stars</option>
<option value="4S">4 Stars</option>
<option value="5S">5 Stars!</option>
</select>
</label>
<textarea name="comments" rows="8" cols="40" placeholder="Comments" required></textarea>
</fieldset>
<fieldset>
<button class="button">Submit</button>
</fieldset>
</form>
</body>
</html>
I beg to differ on your comments. You are getting console errors. Specially, it is erroring out whenever you try to run the parsers on s and s is empty. You need to move the logic into the if clause AFTER you have verified it has a value:
else if (s == null || s == "") {
document.getElementById("valAlert").innerHTML = "Please enter an email address";
return false;
}
else if (s.indexOf("#") < 1 || s.lastindexOf(".") < s.indexOf("#")+ 2 || s.lastindexOf(".")+ 2 >= s.length) {
document.getElementById("valAlert").innerHTML = "This is not a valid email address!";
return false;
}
Here is a Fiddle

Categories

Resources