Check if all values of array are equal to number - javascript

I want to see if there is a better way to check if all values of array are equal to number. I have it working with a foreach but wanted to see if I can do this anyway else?
let valid = true;
$.each(data.resultStatus, function (index, resultStatus) {
if (resultStatus.ResultCode == "2") {
valid = false;
}
});

Related

Run action if contains part of an attr value

I have a input with this
attr('data-disabled-dates','12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022')
And a const which results in tomorrow dynamically, so for this case the result is "16/02/2022"
Now i want to run action if it matches that tomorrow's date is within the attr data-disabled-dates.
So i tried this
if (jQuery(input).attr('data-disabled-dates') == '16/02/2022')
{ console.log('work') } else {
console.log ('not') }
But it only gives me true if the whole sequence is exactly the same, that is, if I put "12/02/2022; 13/02/2022..." if it will give the result, but I only want it to be true if the value I am putting is inside
You can use String.includes() or String.split('; ') to convert string to array and check if it includes the desired value.
if (jQuery(input).attr('data-disabled-dates').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
Working example in vanilla JS
const div = document.querySelector('#data');
const dates = div.getAttribute('data-disabled-dates');
if (dates.includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
// or
if (dates.split('; ').includes('16/02/2022')) {
console.log('work')
} else {
console.log('not')
}
<div id="data" data-disabled-dates="12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022" />
btw https://youmightnotneedjquery.com/
== performs exact string matches, not substring matches.
You can use .split() to split the attribute value into an array, then use .includes() to test if the array contains the date.
if (jQuery(input).data('disabled-dates').split('; ').includes('16/02/2022')) {
console.log("work");
} else {
console.log("not");
}
You can use indexOf to be greater than 0. IndexOf if you need to support IE.
var dataAttrValue = jQuery(input).attr('data-disabled-dates');
var date = '16/02/2022';
if (typeof dataAttrValue !== 'undefined' && dataAttrValue.indexOf(date)) > 0) { console.log('work');
} else {
console.log ('not');
}
OR
jQuery(input).is(“[data-disabled-dates*='16/02/2022']”);
But I suggest using JQuery Data to store and retrieve values from elements.

JQuery: Alternative to each() for conditional check against selected checkbox values

1) Checkboxes has five values: GRA, RRA, FRA, MRA, CHDA
2) Checkbox class Name is oops. Common for all 5.
3) We shall throw an exception if FRA, MRA, CHDA value is not selected
4) Following is snippet i am using to achieve this:
var availability = false;
$(".oops:checked").each(function() {
if($(this).val() === 'FRA' || $(this).val() === 'MRA' || $(this).val() === 'CHDA') {
availability = true;
}
});
if (!availability) {
errors.push('There is no selected among FRA MRA CHRA');
}
Do we have other better approach to handle this instead of using three or operators and check it in each() function?
You can create a array data structure for all the allowed values for the checkbox and check the selected values against them:
var availability = false;
var alloweValues = ['FRA', 'MRA', 'CHDA'];
$(".oops:checked").each(function() {
if(alloweValues.includes($(this).val())) {
availability = true;
}
});
if (!availability) {
errors.push('There is no selected among FRA MRA CHRA');
}
You can further refactor your code to:
var availability = false;
var alloweValues = ['FRA', 'MRA', 'CHDA'];
$(".oops:checked").each(function() {
availability = alloweValues.includes($(this).val());
});
if (!availability) {
errors.push('There is no selected among FRA MRA CHRA');
}
You can also replace includes() with indexOf() like
alloweValues.indexOf($(this).val()) !== -1
As, includes() do not work in IE browser.
Create an array to store each checked value like follows:
var checkvalues=[];
$(".oops:checked").each(function(){
checkvalues.push($(this).val());
});
after that you can use includes() method to check like above code.

Check string for Steam Game Key

basically I need help with checking if a certain string contains a certain pattern:
Here are a few strings in an array:
[ "please use this key: ')D9ad-98ada-jiada-8a8aa'",
"kK8AD-AODK8-ADA7A",
"heres a free game for you guys dkaa2-21ddd-9a9aa-9wada"
]
I need to check the entire array, for keys, that follow this key format from Steam:
Please keep the real keys formats, as told by steam and seen bellow:
AAAAA-BBBBB-CCCCC
AAAAA-BBBBB-CCCCC-DDDDD-EEEEE
I know I would need a for loop like this:
for(var i=0;i<arrayName.length;i++) {
// What should be in here?
}
What should be //In there? To check the strings in the array for that certain Key Pattern.
also, please keep in mind that I first need to remove the text, and then check the key.
Thanks for the help!
I propose you a solution without Regex. You'll have to find by yourself a solution with Regex as a homework
var data = [ "please use this key: ')D9ad-98ada-jiada-8a8aa'",
"kK8AD-AODK8-ADA7A",
"heres a free game for you guys dkaa2-21ddd-9a9aa-9wada"
];
var result = [];
data.forEach(x => {
var flag = true;
var array = x.split("-");
if (array.length === 3 || array.length === 5){
array.forEach(y => {
if (y.length !== 5) flag = false;
});
}
else flag = false;
if (flag === true) result.push(x);
});
console.log(result);

json array check if there does not need to insert in localstorage?

I need to check a JavaScript array to see if there are duplicate values ​​. What is the easiest way to do this ? I just need to check whether the values ​​already exist if there is not need to go into json array.
function cek() {
resi_or_code = document.getElementById('code_or_resi').value;
resi = resi_or_code.split(',');
if($.trim(resi_or_code) != ''){
location.href = base_url + 'resi/' + encodeURIComponent(resi_or_code);
}
if (localStorage.daftar_data){
daftar_data = JSON.parse(localStorage.getItem('daftar_data'));
$("#riwayat").toggle();
}
else {
daftar_data = [];
}
for (y in daftar_data){
var q = daftar_data[y].resis;
for (x in resi){
console.log(q);
if (q === resi[x])
{
console.log('Value exist');
}else{
console.log('Value does not exist');
daftar_data.push({'resis':resi[x]});
localStorage.setItem('daftar_data', JSON.stringify(daftar_data));
}
}
}
}
If i understand your question and code right, you basically have an array of objects where each object has key resis
If that is the case, below code might help
var valueArray = ar.map(function(item) {
return item.resis;
})
// To check for duplicate
if(valueArray.indexOf(value) !== -1) {
// Duplicates
} else {
// No duplicate
}
In your case,
ar would be daftar_data.
I am really not sure what your value is. is it resi?
Basically, you should try replacing your for loop with the above code.
By far the simplest way is to simply sort your array using Array.sort(). This will perform well and reduces you duplicate check to a simple for-loop that compares each value with its neighbor.
Solutions that attempt to avoid sorting will almost certainly scale very badly.
So to recap and show some code:
daftar_data.sort();
for (var index = 0; index < daftar_data.length - 1; index++)
{
if (daftar_data[index] === daftar_data[index+1]) {
// Found a duplicate
}
}
If the natural sort order of the objects don't work for you, supply a function to the sort function, like so:
daftar_data.sort(function(a, b) {
// return any value > 0 if a is greater, < 0 if b is greater
// and 0 if they are equal.
});
Note that in this form, you can actually check for the duplicate in your compare function.

validate 2 dropdowns (only some combinations valid)

I am completely new to JavaScript.
I have size and color dropdowns on a page for users to order a product, but only certain combinations are available i.e. pink is the only color in large sizes.
I thought I'd make an array of allowed sizes and test the user input against these.
If the choice is invalid then I want a popup to tell the user why.
In the real world I'll use SQL & PHP to create the array of allowed choices, in the example below I've hard coded 3 valid choices for testing. Unfortunately the code below doesn't do anything.
I'm sure it's a simple newb mistake. I really don't know what I'm doing :)
Can somebody help me out?
The validation function is supposed to happen when user clicks the form submit...
<form id="form1" name="form1" method="post" onsubmit="return validate_form()"
action="cart.php">
Here's the function:
<script type="text/javascript">
function validate_form() {
var allowed = new Array();
allowed[0]="10,beige";
allowed[1]="10,black";
allowed[2]="10,pink";
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenSizeText+","+chosenColText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
if (allowed[i]=chosenSizeCol) {
found = "true";
}
}
if (found = "false") {
alert( 'The variation you have selected is currently unavailable. Please select another.' );
return false;
} else {
return true;
}
}
</script>
There are a few lines where you use the assignment operator (that is single equals =) instead of one of the equality operators (that is double or triple equals, triple is usually preferred in JavaScript). Example:
if (found = "false") {
Would appear to be the problem at first sight - it's an assignment not a comparison :) use triple equals === instead of single:
if(found === "false") {
Also, consider the following (commented) updates to your code, which reflects more the typical style of JavaScript code:
function validate_form() {
//no need to use new Array(), use array literal instead
var allowed = [
"10,beige",
"10,black",
"10,pink"
];
var chosenColInd = document.getElementById("colID");
var chosenColText = colID.options[colID.selectedIndex].text;
var chosenSizeInd = document.getElementById("sizeID");
var chosenSizeText = sizeID.options[sizeID.selectedIndex].text;
var chosenSizeCol = chosenColText+","+chosenSizeText;
var found = "false";
for ( var i = 0; i < allowed.length; i++ ) {
//use equality operator instead of assignment
if (allowed[i]===chosenSizeCol) {
found = true; //may as well use a boolean rather than string
break; //exit loop early, no need to continue if we've already found
}
}
if (!found) { //no need to do a comparison with already boolean values
alert( 'The variation you have selected is currently unavailable. Please select another.' );
}
//may as well just return found here now that we're using a boolean
return found;
}

Categories

Resources