Check select box values and compare them with an input - javascript

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.’);
}

Related

How to get a tr value within a filter

I having issues grabbing my data within a jquery filter. I have tried finding a solution but haven't been able to find one. I am fairly new with Jquery so I believe this might be a trivial answer.
I like to loop through my array checking it against the cells value, How do I fetch the cells current value / (this) value?
EDIT: Thanks for the help, final solution as follows. Where datesToSearchFor is an array of string dates and nth-child(2) is my dates column in my table.
$("#UnfinishedTable tr").filter(function () {
if (this.id !== 'headerRow') {
var isItThere = false;
var data = $(this).find("td:nth-child(2)").html();//my dates column
datesToSearchFor.forEach(function (entry) {
if (data == entry) {against are array of dates
isItThere = true;
}
});
}
if (isItThere) {//if one was found show the row else hide it
$(this).show()
}
else {
if (this.id !== 'headerRow') {
$(this).hide()
}
}
});
$('#unfinishedTable tr').not('#headerRow').each(function(){
var val = $(this).attr('value');
var src = datesToSearchFor.find(function(n){return n == val;});
$(this).css({'display' : src == null ? 'none' : ''});
});
Filtering is for finding your elements, not acting upon them. After you .filter(), you should put your logic into .each()
$('#UnfinishedTable tr')
.not('#headerRow')
.each(function () {
... // logic
$(this).show();
});
The above example uses .not() as that is closer to what your desired logic is.
The above code seems to be correct, does the console return any errors? Is datesToSearchFor a string vector? Is headerRow the id you assigned to the header tr to ignore it?

Split and find the value exists using JavaScript

I have an array like
[test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840, test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840,test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840]
where I need to split it and find out whether the fourth key in that array of keys has NO or YES or 1. If both NO and YES exists in an array, I need to alert the user that they have both of them in it.
please let me know how to do it in JavaScript.
You can achieve this without split() also:
var array = ['test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840', 'test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840','test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840'];
var arrayStr = array.toString();
if(arrayStr.indexOf('^^^YES') !== -1 && arrayStr.indexOf('^^^NO') !== -1){
alert('You have both of them in it');
}else{
alert('You do not have both of them in it');
}
Assuming that your array contains strings
["test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840", "test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840","test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840"]
You can get the YES/NO keys by mapping the array and splitting it like this
["test1^^^68936^^^2017-06-05^^^274^^^NO^^^location1^^^1840", "test2^^^68766^^^2016-06-05^^^274^^^NO^^^location2^^^1840","test3^^^68966^^^2017-06-05^^^274^^^YES^^^location1^^^1840"].map(function(str){return str.split("^^^")[4]})
Try this
res = arr.join("").match(/NO|YES/g)
if(res.includes("YES") && res.includes("NO")){
console.log("Both present")
}
I tried and got solved
var arrayStr = myarray.toString();
var stringExists = [];
if(arrayStr.indexOf('^^^NO^^^') !== -1) {
stringExists.push('0');
}
if(arrayStr.indexOf('^^^YES^^^') !== -1) {
stringExists.push('1');
}
if (stringExists.length > 1) {
alert("Error");
return;
}
Thanks for all your support guys..

Check if at least one input in array has a value using jQuery/Javascript

I'm trying to check if at least one of my inputs has a value. The code below is currently working to check if all inputs have a value, I need to just check if one in the array contains a value.
var returnValue = true;
var listOfInputs = [
$("#entry_bg"),
$("#entry_carbs"),
$("#entry_bolus"),
$("#entry_correction"),
$("#entry_food"),
$("#entry_notes")
];
listOfInputs.forEach(function(e) {
if (!e.val()) {
returnValue = false;
}
});
if (!returnValue) {
return false;
}
What can I do to achieve this? Any help would be great, thanks!
You can use Array#some:
return listOfInputs.some(function(e) {
return e.val() != '';
});
You should check Array.protoype.some.
some() executes the callback function once for each element present in the array until it finds one where callback returns a truthy value
const hasAtLeastOneValue = listOfInputs.some(input => !!input.val());
It seemed that the simplest solution was to just check for an element that had a value and set returnValue = true.
var returnValue = false;
var listOfInputs = [
$("#entry_bg"),
$("#entry_carbs"),
$("#entry_bolus"),
$("#entry_correction"),
$("#entry_food"),
$("#entry_notes")
];
listOfInputs.forEach(function(e) {
if (e.val()) {
returnValue = true;
}
});
if (!returnValue) {
openErrorModal(".entry_submit", "Add Entry", "You must fill out at least one input in order to add an entry.", "#entry_modal");
return false;
}

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.

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.

Categories