HTML Array script not working (in_Array not defined) - javascript

TL;DR Need help on making this script work
Hi, I've been trying to get this script working with an array structure but it doesn't work and I keep getting the error in_Array not defined. If possible can anyone point out the mistakes I am making even if it minimal. Thanks for your time -Simon
<script>
$traffictick = Array("OFF","ON","OFF");
function tick() {
if (in_Array("ON", $traffictick[1])) {
yellowon();
console.log("Yellow");
$traffictick = Array("OFF,OFF,ON;");
} else if (in_Array("ON", $traffictick[2])) {
redon();
console.log("Red");
$traffictick = Array("OFF,ON,ON;");
} else if (in_Array("ON", $traffictick[2])) {
yellowon();
console.log("Red & Yellow");
$traffictick = Array("ON,OFF,OFF;");
} else if (in_Array("ON", $traffictick[1] & $trafficktick[2])) {
greenon();
console.log("Green");
$traffictick = Array("OFF,ON,OFF;");
}
}
</script>

there is no in_array function in javascript, you have to check manually that your value exist in array or not,
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
Use this function instead of in_array and also you are passing value as a second parameter, you must pass an array.

Related

Get element from this array $scope.pricingList= [[Object { amount="1", type="HOURLY"}], [Object { amount="1", type="HOURLY"}]]

So far I have tried this:
if ($scope.flag) {
$scope.partialPricing.push([$scope.p]);
$scope.flag = false;
} else {
for (var i = 0; i < $scope.partialPricing.length; i++) {
console.log("finding object = " + $scope.partialPricing);
if ($scope.partialPricing[i].type != $scope.p.type) {
$scope.partialPricing.push([$scope.p]);
break;
} else {
console.log("Already Given . Please Clear .");
}
}
}
Problem is when it enters into the else condition, it gets
$scope.partialPricing = [Object Object] and also, $scope.partialPricing[i].type = undefined.
My goal is to prevent user from giving same type twice. Here type is Hourly , Monthly , Weekly.
He can set the value only once. Tell me the solution or any other way i can do it?
Your if condition in the loop won't work properly: it will add the element to the list if its type is different from the first element of the list, independently of all the rest of the list.
The easiest is to make a lookup function as follows:
function lookupByType(type) {
for (var i = 0; i < $scope.partialPricing.length; i++) {
if ($scope.partialPricing[i].type == type) {
return true;
}
}
return false;
}
And then use it as follows (no for loop here):
if (lookupByType($scope.p.type)) {
console.log("Already Given . Please Clear .");
} else {
$scope.partialPricing.push($scope.p);
}
About $scope.flag, I assume you're aware that you use it to bypass the verification, you probably have a good reason for this. However, if the goal is only to insert the first element, there's no need for it: the lookup function will always return false if the list so far is empty.
Edit: You also had a type problem: your pricing list was an array of array of objects, and you used it as an array of objects. You probably want to use the latter, so you need to push($scope.p) rather than push([$scope.p]).
You may switch your else part a bit and check for equality, because that is what you need for exiting the loop. Then break and make your next action according of the check.
if ($scope.flag) {
$scope.partialPricing.push([$scope.p]);
$scope.flag = false;
} else {
var found = false;
for (var i = 0; i < $scope.partialPricing.length; i++) {
console.log("finding object = " + $scope.partialPricing);
if ($scope.partialPricing[i].type === $scope.p.type) {
console.log("Already Given . Please Clear .");
found = true;
break;
}
}
if (!found) {
$scope.partialPricing.push([$scope.p]);
}
}
Otherwise, you could use Array#some and perform a check
if ($scope.flag) {
$scope.partialPricing.push([$scope.p]);
$scope.flag = false;
} else {
var found = false;
if ($scope.partialPricing.some(function (price) { return price.type === $scope.p.type; })) {
console.log("Already Given . Please Clear .");
} else {
$scope.partialPricing.push([$scope.p]);
}
}
Why you need to push "$scope.P" into the partialPricing. Any logic related you handled this line?
$scope.partialPricing.push([$scope.p]);

Can get some values in JSON by key, others I cannot get

I have some JSON:
[{
"cityid":101,
"city":"Alta"
},
{
"cityid":102,
"city":"Bluffdale"
},
{
"cityid":105,
"city":"Draper"
},
{
"cityid":107,
"city":"Holladay"
}]
I can successfully search this array, and get the "city" value, with this function:
function getLocality(cid){
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++)
{
if(clist[i].cityid == cid) {
return clist[i].city;
} else {
}
}
}
My Issue:
When I try to use another function to get the city, instead of getting the cityid, it does not work.
The function I am using to try and get the city id, is as follows:
function getCityid(cid){
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++)
{
if(clist[i].city == cid) {
return clist[i].cityid;
} else {
}
}
}
I am calling the function as so:
getCityid('Draper');
I just opened up the console and tried both of your functions and they both seem to work. Since you didn't provide any sample input/output of your issue, I'll recommend the following:
Verify that you're passing in correct parameters into each function. The getLocality() should take in a cityid and getCityid() should take in a city.
Refrain from using == in javascript as this operator performs type coercion wherein things which are disparate types are "forced" to be the same type in order to perform comparison. You should instead use the === operator which will not perform type coercion. If the two things being compared are different types, it will simply evaluate to false.
Try this.
function getCityid(city) {
var storedlist = localStorage.getItem("citylist");
var clist = JSON.parse(storedlist);
for(var i = 0; i < clist.length; i++){
if(clist[i].city === city) {
return clist[i].cityid;
}
}
}

How do I loop a check for string in a document in Javascript?

I'm trying to make a code that will search for a specific text, and if it is found it will click a button. It needs to check for the string continuously, however I am struggling to find a way for that to happen. I'm a complete newb to coding, so any help is appreciated! :)
var findMe = [
//Test
'Hello!',
];
function findText() {
var text = document.querySelector('div[id=BtnText]');
for (var i = 0; i < findMe.length; i++) {
if (BtnText.match(findMe[i])) {
var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
if (btnDo) {
btnDo.click();
}
}
}
}
Just editing your code a little bit.
I am assuming you have HTML like this?
<div id="BtnText">Hello!</div><input type="submit" value="Click!">
You will to change your code to this
var findMe = [
//Test
'Hello!',
];
function findText() {
var div = document.querySelector('div[id=BtnText]');
for (var i = 0; i < findMe.length; i++) {
if (div.innerText.indexOf(findMe[i]) !== -1) {
var btnDo = document.querySelector('input[type="submit"][value="Click!"]');
if (btnDo) {
if (typeof btnDo.onclick == "function") {
btnDo.onclick.apply(elem);
}
}
return true;
}
}
return false;
}
If you want to check continuously. I recommend using setInterval.
var interval = setInterval(function() {
var textFound = findText();
if(textFound) {
clearInterval(interval);
}
},50);
Regular expression:
(new RegExp('word')).test(str)
(new RegExp(/word/)).test(str)
indexOf:
str.indexOf('word') !== -1
search()
searches a string for a specified value, or regular expression, and returns the position of the match.
var n=str.search("word");
or
var n-str.search(/word/);
if(n>0)
{}
with window.find()
if (window.find("word", true)){}
//code
while(window.find("word",true){
//code
}
Why do you need to perform the check continously?
You should get another approach... Or your script will be blocked by Chrome, for example, if it makes the page non responsible. You can go for a timeout, as Taylor Hakes suggested... Or just call your findText function attached to the onChange event on the div.

Javascript array indexOf returns undefined

When calling my function checkIss(), issFullArray.indexOf(issToCheck) always returns undefined. I've run a .length, output the contents of issFullArray, I can't figure out why it's not working- the array looks fine to me. As you can see below, I've tried explicitly setting issArray as an array and copying the array returned by my getIssList()
function updateIss() {
var issArray = [];
var currService = current.u_business_service;
var currIss = current.u_is_service;
issArray = getIssList(currService).slice(); //getIssList() returns an arry
if (checkIss(issArray, currIss) === false) {
//do stuff
}
}
function checkIss(issFullArray, issToCheck) {
if (issFullArray.indexOf(issToCheck) < 0) {
return false;
} else {
return true;
}
}
Easiest to just loop through the array and compare each value and return true if there is a match otherwise return false. Not much more code and works for all browsers.
function checkIss(issFullArray, issToCheck) {
for(i=0; i<issFullArray.length; i++) {
if(issFullArray[i]==issToCheck) {
return true;
}
}
return false;
}

JQuery .hasClass for multiple values in an if statement

I have a simple if statement as such:
if ($('html').hasClass('m320')) {
// do stuff
}
This works as expected. However, I want to add more classes to the if statement to check if any of the classes are present in the <html> tag. I need it so it's not all of them but just the presence of at least one class but it can be more.
My use case is that I have classes (e.g. m320, m768) added for various viewport widths so I only want to execute certain Jquery if it's a specific width (class).
Here is what i have tried so far:
1.
if ($('html').hasClass('m320', 'm768')) {
// do stuff
}
2.
if ($('html').hasClass('m320')) || ($('html').hasClass('m768')) {
// do stuff
}
3.
if ($('html').hasClass(['m320', 'm768'])) {
// do stuff
}
None of these seem to work though. Not sure what I am doing wrong but most likely my syntax or structure.
You could use is() instead of hasClass():
if ($('html').is('.m320, .m768')) { ... }
You just had some messed up parentheses in your 2nd attempt.
var $html = $("html");
if ($html.hasClass('m320') || $html.hasClass('m768')) {
// do stuff
}
For fun, I wrote a little jQuery add-on method that will check for any one of multiple class names:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
if (this.hasClass(arguments[i])) {
return true;
}
}
return false;
}
Then, in your example, you could use this:
if ($('html').hasAnyClass('m320', 'm768')) {
// do stuff
}
You can pass as many class names as you want.
Here's an enhanced version that also lets you pass multiple class names separated by a space:
$.fn.hasAnyClass = function() {
for (var i = 0; i < arguments.length; i++) {
var classes = arguments[i].split(" ");
for (var j = 0; j < classes.length; j++) {
if (this.hasClass(classes[j])) {
return true;
}
}
}
return false;
}
if ($('html').hasAnyClass('m320 m768')) {
// do stuff
}
Working demo: http://jsfiddle.net/jfriend00/uvtSA/
This may be another solution:
if ($('html').attr('class').match(/m320|m768/)) {
// do stuff
}
according to jsperf.com it's quite fast, too.
For anyone wondering about some of the different performance aspects with all of these different options, I've created a jsperf case here: jsperf
In short, using element.hasClass('class') is the fastest.
Next best bet is using elem.hasClass('classA') || elem.hasClass('classB'). A note on this one: order matters! If the class 'classA' is more likely to be found, list it first! OR condition statements return as soon as one of them is met.
The worst performance by far was using element.is('.class').
Also listed in the jsperf is CyberMonk's function, and Kolja's solution.
Here is a slight variation on answer offered by jfriend00:
$.fn.hasAnyClass = function() {
var classes = arguments[0].split(" ");
for (var i = 0; i < classes.length; i++) {
if (this.hasClass(classes[i])) {
return true;
}
}
return false;
}
Allows use of same syntax as .addClass() and .removeClass(). e.g., .hasAnyClass('m320 m768')
Needs bulletproofing, of course, as it assumes at least one argument.
var classes = $('html')[0].className;
if (classes.indexOf('m320') != -1 || classes.indexOf('m768') != -1) {
//do something
}
The hasClass method will accept an array of class names as an argument, you can do something like this:
$(document).ready(function() {
function filterFilesList() {
var rows = $('.file-row');
var checked = $("#filterControls :checkbox:checked");
if (checked.length) {
var criteriaCollection = [];
checked.each(function() {
criteriaCollection.push($(this).val());
});
rows.each(function() {
var row = $(this);
var rowMatch = row.hasClass(criteriaCollection);
if (rowMatch) {
row.show();
} else {
row.hide(200);
}
});
} else {
rows.each(function() {
$(this).show();
});
}
}
$("#filterControls :checkbox").click(filterFilesList);
filterFilesList();
});
This is in case you need both classes present. For either or logic just use ||
$('el').hasClass('first-class') || $('el').hasClass('second-class')
Feel free to optimize as needed
Try this:
if ($('html').hasClass('class1 class2')) {
// do stuff
}

Categories