Select option value doesnt reach if statement - javascript

So I have question I have select option element:
<select id="item-types__profile" name="item_type_id">
<option selected disabled style="display:none;" value="0"></option>
</select>
And on page load I am triyng to take selected value:
const typesSelect = document.getElementById('item-types__profile')
const test = typesSelect.options[typesSelect.selectedIndex].value;
console.log(test);
if (test === 0) {
console.log('reached');
document.querySelector('.item-fields').style.display = 'none';
}
To console it displays 0, but it doesn't reach if code and it doesn't print out console.log('reached'). I dont understand what could possibly be wrong here?

Triple equality === is a strict comparison which means it also compares the type. Value from the select option is always a string, here it is "0" not 0. You should cast it to int before checking or use double equality ==.

Your condition tests for zero as a number or in Javascript that is know as an integar but the variable test is a string. Should be:
if (test === "0")

Use "==" not "==="
const typesSelect = document.getElementById('item-types__profile')
const test = typesSelect.options[typesSelect.selectedIndex].value;
console.log(test);
if (test == 0) { // here
console.log('reached');
document.querySelector('.item-fields').style.display = 'none';
}

That would simply be because
Value : A String, representing the value of the text field
Simply put value returns a string not a integer so you can do :
if (test === "0") {
console.log('reached');
document.querySelector('.item-fields').style.display = 'none';
}
Alternately :
if (test == 0) {
console.log('reached');
document.querySelector('.item-fields').style.display = 'none';
}
The second one will work even though you get a string because we are not doing strict equal check (so 0 == '0') yields true while 0 === '0' yields false

Related

While loop keep looping even though expression is false

My loop is not quitting when i enter 10. Please help me.
let getGuessess = function(){
let guessedNum = null;
while(guessedNum !== 10){
guessedNum = prompt(`enter number $`);
if(guessedNum === "quit"){
break;
}
}
}
getGuessess();
Change from !== to !=. You're doing a strict equality check on 10 vs '10'.
or !== '10'
Maybe these links can help:
https://www.w3schools.com/js/js_comparisons.asp
I see there that:
!== means not equal value or not equal type
https://www.w3schools.com/jsref/met_win_prompt.asp
And here that, for the prompt function:
Return Value: A String.
I think that it doesn't work because you are comparing a string and an int, they are different types, so your comparison returns False even if you enter 10.

How to get highest value text while field in same class, id and name?

I want to get value from highest while text field in the same class
I have tried to make a script like this but it does not work.
<input class="resbobot" name="BobotY2" id="BobotY2" type="text"value="100">
<input class="resbobot" name="BobotY3" id="BobotY3" type="text"value="80">
<input class="resbobot" name="BobotY4" id="BobotY4" type="text"value="70">
JS
$(".resbobot").each(function() {
if ($(this).val()===100) {
alert($(this).val());
}
The === operator compares value and type. Your code is comparing the string literal '100' against the number 100. You can use the == operator to ignore the type or use parseInt(..) as #RGS suggested.
$(".resbobot").each(function() {
if(parseInt($(this).val())===100)
{
alert($(this).val());
}
});
You have to check text box value with string data type i.e. ' ' or else with integer data type because you are using equal value and equal type operator.
Demo:
http://jsfiddle.net/h9jap3gp/1/
var max = 0
$(".resbobot").each(function() { if ($(this).val()>max) { max = $(this).val()})
alert(max)
=== Checks type and value, == checks value. So "100" === 100 returns false where "100" == 100 returns true.
To find the highest value from the input fields using jQuery, use the following code:
var highestVal = null;
$('.resbobot').each(function(){
var curVal = Number($(this).val());
highestVal = (highestVal === null || highestVal < curVal) ? curVal : highestVal;
});
alert(highestVal);
The above code will work even if the input values are all negative numbers.

Exact value of two variables need to be compared in JQuery

I have the following piece of code:
$j('#row1').find('span.grpid').each(function() {
groupIdNew = groupId.split("~")[0];
var value = $j(this).html();
if (value.match(groupIdNew)){
$j(this).parents('tr').remove();
}
});
Problem is I need the value to exactly equal groupIdNew. (Eg: test_11 should not match test_1 as is the case with .match(), but exactly equal test_11). How do I do this?
Use the double equals sign?
if (value == groupIdNew) {
Use the triple if you want to be strict about the data types.
Don't use match, just compare them:
if(value === groupIdNew){
Or if you need to trim whitespace:
if($j.trim(value) === groupIdNew){
You can use if(value === groupIdNew){
you can use the triple if you want to be strict about the data type
You can just do it using the equal operator (===):
if (value === groupIdNew){
Here's the full code:
$j('#row1').find('span.grpid').each(function() {
groupIdNew = groupId.split("~")[0];
var value = $j(this).html();
if (value === groupIdNew){
$j(this).parents('tr').remove();
}
});
use === operator
if (value === groupIdNew){
$j(this).parents('tr').remove();
}

JS if/else trouble

I have a simple code:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#continue").click(function() {
var value = jQuery('#continue').attr('value')
alert (value);
if (value='next'){
jQuery('#msg_title').html('blablabla');
jQuery('#msg').html('blablabla'');
jQuery('#continue').attr('value','removeConfig');
value = jQuery('#continue').attr('value');
}
else if (value='removeConfig') {
jQuery('#msg_title').html('It Works!');
}
else {
alert ('Something wrong')
}
return false;
});
});
</script>
It works well in firs if phase, changes button's value (as I see from alert), but doesn't make else if and else statements.
Your comparison operator is wrong: if (value='next') should be if (value == 'next'){ or if (value === 'next'){.
Note the extra = signs.
You need ==
(value='next'){
should be:
(value == 'next'){
You are testing if ('next') { which is always true. Only string the evaluates to false is empty string, ""
Use ==, not =. A single = is an assignment operator, which means it's assigning "next" to value, then testing if value is false, not if value equals next
You need double equals signs as singles will return true in this case:
if (value =="next")
Single = is an assignment operator and double == is a comparison operator. Since you were using an assignment operator and setting the variable to a non falsy value the first if statement resolved to true.

'' equals false in Javascript? What would be the safest way to distinguish between '' and boolean false?

We use an external API whcih returns '' or boolean false while Javascript seems to find the both equal.
for example:
var x = '';
if (!x) {
alert(x); // the alert box is shown - empty
}
if (x=='') {
alert(x); // the alert box is shown here too - empty
}
var z = false;
if (!z) {
alert(z); // the alert box is shown - displays 'false'
}
if (z=='') {
alert(z); // the alert box is shown here too - displays 'false'
}
How can we distinguish between the two?
Use the triple equal
if (x===false) //false as expected
if (z==='') //false as expected
A double equal will do type casting, while triple equal will not. So:
0 == "0" //true
0 === "0" //false, since the first is an int, and the second is a string
var typeX = typeof(x);
var typeZ = typeof(z);
if (typeX == 'string' && x == '')
else if (typeX == 'boolean' && !typeX)
I like Peirix's answer too, but here is an alternative.
as mentioned by peirix: tripple equal signs check both the value and the type
1 == '1' // true
1 === '1' // false
For avoid this questions use jslint validator. It helps for find unsafe operations.

Categories

Resources