JS Check Jquery inArray - javascript

I would like to use a onchange state on a select element to check if the value of the select is in an array.
I tried this :
function statutEmployeur(){
statliste = [];
statliste.push(1);
statliste.push(2);
statliste.push(5);
statid = jQuery("#statut").val();
if(jQuery.inArray(statid,statliste)>-1){
alert('inside array');
}else {
alert('outside array');
}
}
Each value that I tried are outside of the array.
Anybody can help me ?
Thanks

as pointed out by Stryner in the comments, try running your .val() through parseInt() to ensure you nave a numerical value (and not a string)
statid = jQuery("#statut").val();
to:
statid = parseInt(jQuery("#statut").val(), 10);
working fiddle: http://jsbin.com/maqesupuka/edit?html,js,console,output
the problem is you're searching in the array for a type of string (default type of inputs), but your array only contains numbers. You could either make your array into numbers, or do a type conversion like above to ensure you're working with the same type.

Related

How to access the first two digits of a number

I want to access the first two digits of a number, and i have tried using substring, substr and slice but none of them work. It's throwing an error saying substring is not defined.
render() {
let trial123 = this.props.buildInfo["abc.version"];
var str = trial123.toString();
var strFirstThree = str.substring(0,3);
console.log(strFirstThree);
}
I have tried the above code
output of(above code)
trial123=19.0.0.1
I need only 19.0
How can i achieve this?
I would split it by dot and then take the first two elements:
const trial = "19.0.0.1"
console.log(trial.split(".").slice(0, 2).join("."))
// 19.0
You could just split and then join:
const [ first, second ] = trial123.split('.');
const result = [ first, second ].join('.');
I have added a code snippet of the work: (explanation comes after it, line by line).
function getFakePropValue(){
return Math.round(Math.random()) == 0 ? "19.0.0.1" : null;
}
let trial123 = getFakePropValue() || "";
//var str = trial123.toString();
// is the toString() really necessary? aren't you passing it along as a String already?
var strFirstThree = trial123.split('.');
//var strFirstThree = str.substring(0,3);
//I wouldn't use substring , what if the address 191.0.0.1 ?
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
Because you are using React, the props value was faked with the function getFakePropValue. The code inside is irrelevant, what I am doing is returning a String randomly, in case you have allowed in your React Component for the prop to be empty. This is to show how you an create minimal robust code to avoid having exceptions.
Moving on, the following is a safety net to make sure the variable trial123 always has a string value, even if it's "".
let trial123 = getFakePropValue() || "";
That means that if the function returns something like null , the boolean expression will execute the second apart, and return an empty string "" and that will be the value for trial123.
Moving on, the line where you convert to toString I have removed, I assume you are already getting the value in string format. Next.
var strFirstThree = trial123.split('.');
That creates an array where each position holds a part of the IP addrss. So 19.0.0.1 would become [19,0,0,1] that's thanks to the split by the delimiter . . Next.
if(strFirstThree.length >= 2)
console.log(strFirstThree.splice(0,2).join("."));
else
console.error("prop was empty");
This last piece of code uses the conditional if to make sure that my array has values before I try to splice it and join. The conditional is not to avoid an exception, since splice and join on empty arrays just returns an empty string. It's rather for you to be able to raise an error or something if needed. So if the array has values, I keep the first two positions with splice(0,2) and then join that array with a '.'. I recommend it more than the substr method you were going for because what if you get a number that's 191.0.0.1 then the substr would return the wrong string back, but with splice and join that would never happen.
Things to improve
I would strongly suggest using more human comprehensible variables (reflect their use in the code)
The right path for prop value checking is through Prop.Types, super easy to use, very helpful.
Happy coding!

How to Check the variable value is [""] in JavaScript

Example:
When I check a variable containing this value [""] it returns false.
var th=[]
th.push("");
if($("#multiselect").val()==th)
It returns always false.
Thank you.
Edit 1:
changed Var to var. It was a typo.
Edit 2:
Actually, the problem I faced was I was trying to get the value from a multi-select input. The multi-select input sometimes returns values as [""] even I haven't selected any values basically it's a plugin. So I was confused and I thought [""] is a fixed primitive value like 1, 10, "bla blah",.. So I tried to compare it with the same array as the right-hand side of the '=' operator.
It was stupid. Now I posted the solution to my problem and I explained my stupidity.
there are two things:
Change Var to var
You can use includes method of Array as:
var th = [] <==== chnage Var to var
th.push("");
if(th.includes($("#multiselect").val())) { <=== you can use includes method of array
// DO whatever you want
}
Make sure var is lowercased.
You are accessing th as an array, so you’ll need to specify the index of the value you are checking: th[0]
Use triple equals, too: .val()===th[0]
Double check the jquery docs if you’re still running into trouble.
Happy coding!
A couple of things to consider:
You have a typo in the code above; var is valid; Var is invalid.
Browser will aptly complain to solve this typo.
You are comparing an array to DOM value; this will always be false.
DOM is a costly process. Unless the value associated is dynamic, its better to read once, store value into a variable and continue processing instead of reading from DOM always.
You could choose to try something on these lines:
let arr = [1,2,3,4];
let domValue = $("#multiselect").val();
arr.push(5);
arr.map((el, ix) => {
if el === domValue return true; //or choose to do something else here.
});
var th=[]; //It is var not Var
th.push("");
if($("#multiselect").val()==th[0]) // change th to th[0]
I am unable to comment so having to use an answer for now. Are you trying to check if an array has any values? If so you can use
if(th.length){
// do something
}
If you want to check a normal variable for empty string you can simply use
if(th == “”){
//do something
}
I found the solution after a couple of days when I posted this question. Now I can feel how stupid this question was.
Anyway, I'm answering this question so it might help others.
Answer to my question:
When two non-primitive datatype objects(which is the Array here) are compared using an assignment operator, it compares its reference of the object. So the object creation of both arrays would be different. If I want to check the array has [""] value, I should do something like the below.
function isArrValEmptyCheck(value) {
return !value || !(value instanceof Array) || value.length == 0 || value.length == 1 && value[0] == '';
}
console.log(isArrValEmptyCheck([""]));//returns true
console.log(isArrValEmptyCheck(["value1"]));//returns false
Sorry for the late response. Thanks to everyone who tried to help me.

_.findWhere from underscorejs to JQuery

I am trying to implement this code: http://jsfiddle.net/wQysh/351/ in my project.
Everything is fine except for the line:
t = _.findWhere(sc, { id : Number(a.trim()) });
They have used underscorejs and I want to translate this to JQuery without using another lib.
I went through the doc and it stated:
findWhere_.findWhere(list, properties)
Looks through the list and returns the first value that matches all of the key-value pairs listed in properties.
If no match is found, or if list is empty, undefined will be returned.
But still I am confused about this since I am not sure what to return exactly (as first value). Can anyone give me a JQuery alternative to that line?
Thanks in advance..
If you don't the generic nature of _.findWhere() you can use a simple while loop, and compare the id to the numeric value of a (fiddle):
t = 0; // t is used as a counter
aValue = Number(a.trim()); // assign the value to a variable instead of iterating it
while (t < sc.length && sc[t].id !== aValue) { t++; }; // find the index where the id is the as the aValue
t < sc.length && toSet.push(sc[t]); // if t is less the sc.length we found the item in the array
If you need a findWhere without underscore try this gist.
I also used this example in my project. And also needed use JQuery instead of Underscore.
Here is my solution:
t = sc.filter(function (el) { return el.id === a });
It work perfect for me;
If you use number for ids, you can also convert a to integer
t = sc.filter(function (el) { return el.id === parseInt(a, 10) });

Javascript replace works in console, not in code

I've been trying to setup a small booking system however I'm stuck. Basically, I add all the seat numbers that want to be booked into a string eg (a22~b20~f10). However when a seat is deselected it needs to be removed from the string. I have tried using .replace but to no avail, even in the console.
I then tried the code below. It works brilliantly in the console, but not at all in my code.
seatNumbersToBook.split(seatNumber+"~").join("");
The full function is here
var seatNumbersToBook = "";
function calcSeats(calc, seatNumber){
if(amountSeatsToBeBooked != 0 && seatNumber != "NaN" && calc == "-1"){
seatNumbersToBook = seatNumber + "~" + seatNumbersToBook;
}
if(calc == "+1"){
//remove from seatNumbersToBook array
seatNumbersToBook.split(seatNumber+"~").join("");
console.log(seatNumber);
}
// despite removing seat number from array, still MUST check in array to see if the seatnumber has already been recorded
amountSeatsToBeBooked = eval(amountSeatsToBeBooked + calc);
$("#remainingSeatsToBeBooked").html(amountSeatsToBeBooked);
console.log(seatNumbersToBook);
return amountSeatsToBeBooked;
}
Thanks a lot in advance!!
You do the split() then join() but don't assign the result back to seatNumbersToBook, so seatNumbersToBook is still old value
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split and https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
String.prototype.split() and Array.prototype.join() does not change the string or array itself but returns a new string or array

How to turn a returned object into a string?

I'm using an input that takes a number that a user enters and converts it to a dollar amount when the blur event fires.
The issue I am having is that the browser seems to keep previously submitted values intact with their dollar signs. So if the user selects a previously entered value of '$25000' from the drop down list, when the blur event fires again it adds in the '$' so I get '$$25000'
In order to stop this, i've made an adjustment to the string value if it contains 2 '$'s on blur:
HTML:
<input type="text" value="$5,000" id="dollar-amount-goal" />
Javascript:
var valueOnBlur = $('#dollar-amount-goal').val();
if(valueOnBlur.charAt(1) === '$'){
valueOnBlur = $('#dollar-amount-goal').val(valueOnBlur.substr(1));
}
console.log(typeof( valueOnBlur ));
The result of the typeof statement above when the string checking is run is 'object'. any time after it comes out as 'string' (which is what I want).
My question: How do I make the "valueOnBlur = $('#dollar-amount-goal').val(valueOnBlur.substr(1));" statement return a string when it's run?
Thanks
Try changing this:
valueOnBlur = $('#dollar-amount-goal').val(valueOnBlur.substr(1));
To this:
valueOnBlur = $('#dollar-amount-goal').val(valueOnBlur.substr(1)).val();
You want the value of the $('#dollar-amount-goal') and not the jQuery object that $('#dollar-amount-goal') will return

Categories

Resources