check multiple values in an if statement in jquery/javascript - javascript

I am trying to if the value of an input box is blank or not by doing the below:
var id = $(this).attr('id').substr(3);
var lengthname = $("#input_name_"+id).val().length;
var lengthrss = $("#input_rss_"+id).val().length;
if (lengthrss!=0 || lengthname!=0)
{
// do something
}
else
{
alert('Values cannot be blank');
}
For some reason it is not doing the OR however if the user enters both values as blanks then the alert comes up??

What you are looking for is an AND operation, not OR. The valid case is when both lengths are non-zero:
if (lengthrss!=0 && lengthname!=0)
{
// do something
}
Alternatively:
if (lengthrss==0 || lengthname==0)
{
alert('Values cannot be blank');
}
For reference: De Morgan's laws

Related

Conditional javascript input field validation

I am currently working on a project that requires me to do a javascript form validation on a form that contains conditional input fields ( the visitor can choose whether to log in via a user number or email address ). Both input fields are separate and I need to do the following:
If visitor chooses to log in via option A ( user number ), the validation should only take into account the id of input field A ( the user number ) and not require validation for the other field ( email address ).
And vice versa, if visitor chooses option B.
The code I am currently using for validation:
function empty() {
var x;
x = document.getElementById("user_number").value;
if (x == "") {
MsgBox('Your user number is required.', 'ERROR');
return false;
}
var y;
y = document.getElementById("email").value;
if (y == "") {
MsgBox('Your email address is required.', 'ERROR');
return false;
}
}
And the form trigger event:
<form method="POST" id="accordion-top-form" action="" onsubmit="return empty();">
I need to expand the current script to check if either field A or field B has been filled in when submitting the form ( and then automatically disable validation for the other field ).
How do I do that?
You could use the following:
var forms = {
user: 0,
email: 1
};
function whichForm() {
var userForm = document.getElementById("user_number").value;
var emailForm = document.getElementById("email").value;
if (userForm && emailForm) {
//user wrote in both forms, something is wrong
} else if (!userForm && !emailForm) {
//user didn't fill in any form
} else {
return userForm ? forms.user : forms.email;
}
}
function empty(form) {
if (form === forms.user) {
// check if the user number form is empty
var userForm = document.getElementById("user_number").value;
if(userForm.trim() === "") {
// possibly do more validation
// return true or false based on whether you want to submit
}
} else if (form === forms.email) {
// check if the email form is empty
var emailForm = document.getElementById("email").value;
if(emailForm.trim() === "") {
// possibly do more validation
// return true or false based on whether you want to submit
}
} else {
// something is wrong, invalid parameter,
// handle here
return false
}
}
function validate() {
return empty(whichForm());
}
And change your form so that it calls return validate() inline or just validate as a submit handler.
Sounds like this would be enough?
I would personally not call the function empty since you want to return true to allow submission
function empty() {
var x = document.getElementById("user_number").value,
y = document.getElementById("email").value;
x = x?x.trim()|| ""; // handle null and all blanks
y = y?y.trim()|| "";
if (x === "" && y === "") {
alert("Please enter user number or email")
return false;
}
// optional
if (x && y) { // both entered
alert("Please enter EITHER user number or email")
return false;
}
if (x) return isValidUser(x); // each of these functions needs to return boolean
if (y) return isValidEmail(y);
// likely not going to happen
return false;
}
You can test if both are empty
function empty() {
var a = document.getElementById("user_number").value,
b = document.getElementById("email").value;
if ("" == a && "" == b) return MsgBox("Your user number or mibile is required.", "ERROR"), !1
};
Code do it in this way:
function empty() {
var x = document.getElementById("user_number").value,
y = document.getElementById("email").value;
if (!x && !y) {
alert('You should choose email address or number');
return false;
}
return true;
}
Proposed solution:
Check which of the two input fields is filled up:
var inputA = document.getElementById('A').value;
var inputB = document.getElementById('B').value;
if ((inputA !== "") || (inputA !== NaN) || (inputA !== undefined)) {
//execute code for the user number
}
else if ((inputB !== "") || (inputB !== NaN) || (inputB !== undefined)) {
//execute code for the email
}
else {
//display an error saying none of the two fields were used
}
Recommendation: Most websites would only use 1 input because it looks a lot cleaner. And the place holder text can specify to the user what input options he should put in:
<input type="text" id="input1" placeholder="user number or email">
Proposed Solution: Check if the user input has a # symbole:
var input1 = document.getElementById("input1").value;
var emailInput = input1.includes('#');//returns a boolean with a value of true
//if '#' was found in the string input1
if (emailInput) {
//execute the code for the email input
} else {
//execute the code for the userID input
}
Explanation:
I assumed that you wanted to use the same input field inside your <form ...> tag regardless if the user is using an email or an id number to log in. From that, what I saw as most logical is to just find something that is unique to one of those inputs, and base the logic of your code on whether that unique element existed in the input provided.
AKA since emails always have the # symbol, verifying if this exists in the provided string or not should be enough to verify if the user used an email or id number to attempt to login.
Let me know if that helped :).

Display error if element in array have 0 value

i have an array in javascript using map function. it collect data from a loop drop down. i just want to ask how to check if array have 0 then display error message. "One of the data not selected"
the array code :
var self_assess_check = $("select[name='self_assess[]'] option:selected").map(function() {
return $(this).text();
}).get();
alert(self_assess_check);
if i alert the array alert(self_assess_check); it produce : 1,0,2,-,-,5,0
how can i make if condition to check if whole array have 0 value then show error message
what i made:
if ((self_assess_check) == "0"){
alert("One of the data not selected");
return false;
}else{
var r=confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r==true){
}else{
return false;
}
}
i think my if condition not correct since it will go to else and skip if.tq
Use $.inArray()
if ($.inArray('0', self_assess_check) != -1) {
alert("One of the data not selected");
return false;
} else {
var r = confirm("Make sure all answer is correct. Once Submit it cannot be changed");
if (r == true) {
} else {
return false;
}
}
Note: Array.indexOf() is not used since IE8 might have to be supported.
You can check Array as below code.
function isUndefined(targetO){
return (targetO == 'undefined' || targetO == undefined);
} if(!isUndefined(self_assess_check){ if(self_assess_check.length!=0){alert("Array contain values"); }}
This will work.

Javascript if value is in array else in next array

I have found a few posts on here with similar questions but not entirely the same as what I am trying. I am currently using a simple if statement that checks the data the user enters then checks to see if it starts with a number of different values. I am doing this with the following:
var value = string;
var value = value.toLowerCase();
country = "NONE";
county = "NONE";
if (value.indexOf('ba1 ') == 0 || value.indexOf('ba2 ') == 0 || value.indexOf('ba3 ') == 0) { //CHECK AVON (MAINLAND UK) UK.AVON
country = "UK";
county = "UK.AVON";
} else if(value.indexOf('lu') == 0){//CHECK BEDFORDSHIRE (MAINLAND UK) UK.BEDS
country = "UK";
county = "UK.BEDS";
}
I have about 20-30 different if, else statements that are basically checking the post code entered and finding the county associated. However some of these if statements are incredibly long so I would like to store the values inside an array and then in the if statement simply check value.indexOf() for each of the array values.
So in the above example I would have an array as follows for the statement:
var avon = new Array('ba1 ','ba 2','ba3 ');
then inside the indexOf() use each value
Would this be possible with minimal script or am I going to need to make a function for this to work? I am ideally wanting to keep the array inside the if statement instead of querying for each array value.
You can use the some Array method (though you might need to shim it for legacy environments):
var value = string.toLowerCase(),
country = "NONE",
county = "NONE";
if (['ba1 ','ba 2','ba3 '].some(function(str) {
return value.slice(0, str.length) === str;
})) {
country = "UK";
county = "UK.AVON";
}
(using a more performant How to check if a string "StartsWith" another string? implementation also)
For an even shorter condition, you might also resort to regex (anchor and alternation):
if (/^ba(1 | 2|3 )/i.test(string)) { … }
No, it doesn’t exist, but you can make a function to do just that:
function containsAny(string, substrings) {
for(var i = 0; i < substrings.length; i++) {
if(string.indexOf(substrings[i]) !== -1) {
return true;
}
}
return false;
}
Alternatively, there’s a regular expression:
/ba[123] /.test(value)
My recomendation is to rethink your approach and use regular expressions instead of indexOf.
But if you really need it, you can use the following method:
function checkStart(value, acceptableStarts){
for (var i=0; i<acceptableStarts.length; i++) {
if (value.indexOf(acceptableStarts[i]) == 0) {
return true;
}
}
return false;
}
Your previous usage turns into:
if (checkStart(value, ['ba1', ba2 ', 'ba3'])) {
country = 'UK';
}
Even better you can generalize stuff, like this:
var countryPrefixes = {
'UK' : ['ba1','ba2 ', 'ba3'],
'FR' : ['fa2','fa2']
}
for (var key in countryPrefixes) {
if (checkStart(value, countryPrefixes[key]) {
country = key;
}
}
I'd forget using hard-coded logic for this, and just use data:
var countyMapping = {
'BA1': 'UK.AVON',
'BA2': 'UK.AVON',
'BA3': 'UK.AVON',
'LU': 'UK.BEDS',
...
};
Take successive characters off the right hand side of the postcode and do a trivial lookup in the table until you get a match. Four or so lines of code ought to do it:
function getCounty(str) {
while (str.length) {
var res = countyMapping[str];
if (res !== undefined) return res;
str = str.slice(0, -1);
}
}
I'd suggest normalising your strings first to ensure that the space between the two halves of the postcode is present and in the right place.
For extra bonus points, get the table out of a database so you don't have to modify your code when Scotland gets thrown out of leaves the UK ;-)

Including a for loop in an if statement

I'm building an application in which I want to display some errors when a user enters invalid values in an input box. A correct value is appended as 'entry' to a div if no errors were found. In total there are 3 cases when to display errors:
The input value is empty
The input value is a number
The input value already exists
These errors are displayed with if else statements.
1.and 2. were easy, but the problem case (3.) only validates against the first element of class .cat_entry.
if(cat_input == '') { // generate errors
errorDisplay(error_input_empty);
} else if(!isNaN(cat_input)) {
errorDisplay(error_input_number);
} else if($('.cat_entry') == cat_input) { // THIS IS THE PROBLEMATIC LINE
// .cat_entry is the class of the entries that have been appended
errorDisplay(error_duplicate);
} else {
// stuff
};
So I believe I need a for loop/ .each() (no problem so far), but how do I include this as a condition in an if statement? Something like.. if( for(i=0;i<$('.cat_entry').length;i++) { ... }; ... How to return true (or something similar) when one of the entries matches the input value, then pass the return value to the if statement?
EDIT: here is a jsFiddle with the relevant code. I updated it with $.inArray() method. I'd like to try and use this instead of a for / .each() loop.
You can try this:
var a=$('.cat_entry'),o={};
for(i=0;i<a.length;i++) {
var s=a[i].val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
or
var o={};
$('.cat_entry').each(function(){
var s=$(this).val();
if(s in o){
errorDisplay(error_duplicate);
return;
}
o[s]=true;
}
You can actually use the jQuery inArray function for this, such as:
else if($.inArray(cat_input, $('.cat_entry') != -1)
}
The solution was to add this to the function:
var isDuplicate = false;
$('.cat_entry').each(function() {
if(!$(this).text().indexOf(cat_input)) {
isDuplicate = true;
}
// And in the if else loop:
else if(isDuplicate == true)
//and just before the function ends
isDuplicate = false;
Thanks to all for the help you offered.

Array.push causes program to have errors

I followed the advice from a previous question to get my promps to add values to an array, but it has caused my program to throw up True values when they are not.
HIGHEST_GRADE = 7;
LOWEST_GRADE = 0;
var course = new Array();
var grade = new Array();
while(confirm("Would you like to add a course?")){
course.push( prompt("Enter the course code. Example - ABC1234") );
};
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
if (isNaN(grade)) {
alert('Invalid Grade');
}
if (LOWEST_GRADE > grade || HIGHEST_GRADE < grade) {
alert('Invalid Grade');
}
I have it set to make sure the entered text matches the conditions, but since the .push was added the whole thing stuffs up.
I get an Invalid Course Code error, something is playing up with that.
The Array is used to store multiple courses, which is fine. But, since it's an array, you need to access each position of it to validate each individual course, using a loop:
var courses = new Array(); // use the name courses instead, to indicate that it's a collection
for (var i = 0; i < courses.length; i++) {
var course = courses[i];
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (course.length !== 7) {
alert ('Invalid Course Code');
}
if (upperTest !== upperTest.toUpperCase()) {
alert ('Invalid Course Code');
}
if (isNaN(integerTest)) {
alert('Invalid Course Code');
}
}
This will validate every course that is in the Array. Otherwise, when you test courses.length, you'll be validating the number of elements in the array, not the number of characters of each course.
The same needs to be done for the grades array.
Do you want to validate entered course code? In such case you need to do it with the item not with the whole array:
while (confirm("...")) {
var courseCode = prompt("...");
var upperTest = course.slice(0,3);
var integerTest = course.slice(4,7);
if (courseCode.length !== 7) {
alert ('Invalid Course Code');
continue;
}
// place your other if's here
courses.push(courseCode);
}

Categories