Display error if element in array have 0 value - javascript

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.

Related

check if two values are meaningfully equal using === not working in javascript

I want to check if two values are meaningfully equal using javascript but it is not working when a button is clicked. Below is my attempt
jQuery(document).ready(function(){
jQuery(':button').click(function () {
if (this.id == 'click') {
alert('this button was clicked');
$('input[type=text]').blur(function(){
$(this).val($.trim($(this).val()));
});//trim white spaces
var name = localStorage.getItem("inputName");
if(document.getElementById('inputName').value === name ){
alert('both values are equal'); //but it never gets executed when the two values are equal
}else {
alert('not showing anything'); //always executing this line
}
}else {
}
});
});
how can I execute the if block only when the two values are equal.
Try to get the value with .val() and check which type var name has
You can do normal comparison == for this task or do a checking parse to use === instead
CODE SNIPPET
$('.click').on("click", function() {
var input = $('#inputName').val();
var name = "hello";
if (input == name) {
alert('both values are equal');
} else {
alert('both are not equal');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="click" id="click">Click</button>
<input type=text id="inputName" />
if(some.value === name && other.value === eman ) {
execute();
}
That doesn't solve any of the "listener" problems you may have, but that is how you require two conditions to be true (or more if you continue the pattern).
Also, || is for "or" conditions.
For specific cases I have used an "additive" solution where both conditions being true sets a variable to '2', just one condition being true setting that variable to 1, and none of the conditions being true sets that variable to 0. That helps when one and only one condition must be true...

If Else Conditionals within Function in JavaScript

I'm having issues with conditionals. I want to return the index where pattern starts in string (or -1 if not found). The search is to be case sensitive if the 3rd parameter is true otherwise it is case insensitive.
Examples
index("abAB12","AB",true) returns 2 but index("abAB12","AB",false) returns 0
index("abAB12","BA",true) returns -1 and index("abAB12","BA",false) returns 1
Any idea how I can accomplish this?
This is my code so far
var s = "abAB12"
var p = "AB"
var cs = true
function index(string, pattern, caseSensitive) {
if (pattern) {
var found = false;
if (caseSensitive = false) {
if (string.indexOf(pattern.) >= 0) {
found = true;
}
return (found);
else {
return ("");
}
} else if (caseSensitive = true) {
if (string.toLowerCase().indexOf(pattern.toLowerCase()) >= 0) {
found = true;
}
return (found);
} else {
return ("");
}
}
}
alert(index(s, p, cs));
Fiddle at http://jsfiddle.net/AfDFb/1/
You have some mistype in your code. On the 15th line you have
}
return (found);
else {
This is not not valid. Change it to
return (found);
}
else {
There is another one.
if (caseSensitive = false) {
= used for assignment. You need to use == in if statements when comparing.
Also on the 13th line, there's an extra . after pattern. Remove it.
if (string.indexOf(pattern.) >= 0) {
Your fiddle example
You can use string.search() with a regular expression to accomplish this in one liner:
function index(input, key, caseMatters) {
return input.search(new RegExp(key, caseMatters ? '' : 'i'));
}
Now you can:
index("abAB12","AB",true); // returns 2
index("abAB12","AB",false); // returns 0
index("abAB12","BA",true); // returns -1
index("abAB12","BA",false); // returns 1
You need to use double equals sign == in your if, else statements.
if(caseSensitive == false)
And
if(caseSensitive == true)
You are assigning value inside if condition instead of comparing it.
Try
if (caseSensitive == false) {
and
if(caseSensitive == true)
You'd better use search :
'abAB12'.search(/AB/); // 2
'abAB12'.search(/AB/i); // 0
'abAB12'.search(/BA/); // -1
'abAB12'.search(/BA/i); // 1
The i flag means "case insensitive" ( insensible à la casse :D ).

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.

Check select box values and compare them with an input

I would like to check if a textfield, newTeamName is already in a list of teamnames stored in a select box. Unfortunately, my code does not work - what's wrong with it? Oh and I have no console problems.
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (form.newTeamName.value in optionList) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Small Update:
Oh and my form.name.value's work fine as they work for other if statements.
optionList is an array in used for object properties(or numeric array indices), you can use indexOf to test if a value is in an array
optionList = [];
$('#chooseTeam option').each(function() {
optionList.push($(this).val())
});
if (optionList.indexOf(form.newTeamName.value) > -1) {
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
Fixed it.
$('#chooseTeam option').each(function() {
if (form.newTeamName.value == $(this).val()){
$("#text-error").html("Team exists");
$('#text-error').fadeIn(400).delay(3200).fadeOut(800);
return false;
}
});
try something like this
my_array = Array();
//To find if a value or element exists in an array
if (my_array.indexOf(‘find_this_value’) != -1)
{
alert(‘Value exists in array.’);
}
//To find if a value or element DOES NOT exist in an array
if (my_array.indexOf(‘find_this_value’) == -1)
{
alert(‘Value does not exist in array.’);
}

Attempting to compare textbox with array element

I am trying to compare user entered text in a textbox with an element in an array but am having difficulties.
function checkAns()
{
var str = imageArray[randNum];
var n = str.indexOf(document.getElementById('textBox').value);
if(n == -1)
{
alert("Wrong Answer")
}
else
{
alert("Right Answer")
}
}
The user input should either match part of the the specified string in the array element and return Right Answer or not match at all and return Wrong Answer.
<input type=”text” id=”textBox” value=””>
<input type=”button” value=”Check” onclick=”checkAns()”>
I added the code for my textbox and button if that is useful.
Please check what exactly you need to get. This:
if (document.getElementById('textBox').value === str) {
// text from array element is the same as in value
} else {
// ... differs from value
}
Or this:
if (str.indexOf(document.getElementById('textBox').value) > -1) {
// text from value exists in array element
} else {
// ... does not exist
}
Or maybe this:
if (document.getElementById('textBox').value.indexOf(str) > -1) {
// text from array element exists in value
} else {
// ... does not exist
}

Categories