My if and else statement always think it's -and [duplicate] - javascript

This question already has answers here:
IF Statement Always True
(3 answers)
Closed 4 years ago.
I have a selector on my page that has -and or -or. I'd like to change the content of a div depending on what users choose with -And or -Or.
My if and else statements aren't working right now, well it's almost working it just always add -And. It looks as if it always see's -And?
First time I'm trying to use an if and else statement and I think I made mistake.
<script>
function Andor' + count + '(selTag) {
var x = selTag.options[selTag.selectedIndex].text;
if (x = '-and'){
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " ";
} else {
document.getElementById("and-or-' + count + '").innerHTML = " " + x + " (";
}
}
</script>

You use one =, which is 'assign'. You want === (or ==) for 'equals'.
You do the same as: var example = 'foo';. You set the value to a string ('-and'), which always results in true, which makes it look like it's true.
What you want is example=='foo' to check if the content of example equals 'foo'.
Suggested reading material: https://codeburst.io/javascript-double-equals-vs-triple-equals-61d4ce5a121a

Related

How to show text into span In javascript with alphanumaric $("#abcd"+counter) [duplicate]

This question already has answers here:
JavaScript object: access variable property by name as string [duplicate]
(3 answers)
Closed 6 years ago.
I am trying to get value from $.each and using counter for HTML entity <span>
var counter =1;
$.each(catCounting, function(){
alert(catCounting.(countCat+counter));
$('#countCategory'+counter).html("("+catCounting.(countCat+counter)+")");
counter++;
});
//alert(counter);
}
I'm not entirely sure, but I believe you're trying to get the value at a specific index of catCounting. If this is the case, you need to use the index syntax to find the value which is [] rahter than ().
You don't need to use a . after the variable to do this, so catCounting.(countCat + counter) should become catCounting[countCat + counter]
var counter = 1;
$.each(catCounting, function(){
alert(catCounting[countCat+counter]));
$('#countCategory' + counter).html(
"(" + catCounting[countCat + counter] + ")"
);
counter++;
});

"Try...Catch" Block not Working with parseInt()

What I'm trying to do:
I have a javascript program that, when a button is clicked, takes in 4 strings from 4 text boxes in a form, and outputs those strings into a formatted textarea.
function testResults(form){
var errorhandle1 = parseInt(document.myForm.Item_Code.value);
var errorhandle2 = parseInt(document.myForm.Item_Cost.value);
var errorhandle3 = parseInt(document.myForm.Quantity.value);
//above variables are for error handling.
var d = " ";
var subtotal = parseInt(form.Item_Cost.value) * parseInt(form.Quantity.value);
var subtotalValue = parseInt(document.myForm.Subtotal.value);
var testVar = "Item Code: " + form.Item_Code.value + d +
"Item Name: " + form.Item_Name.value + d +
"Item Cost: " + form.Item_Cost.value + d +
"Quantity: " + form.Quantity.value + '\n';
document.myForm.myTextarea.value += testVar;
document.myForm.Subtotal.value = parseInt(subtotal) + subtotalValue;
document.myForm.Sales_Tax.value = document.myForm.Subtotal.value * salestax;
document.myForm.Total.value = parseInt(document.myForm.Subtotal.value) + parseFloat(document.myForm.Sales_Tax.value);
}
The above code works just fine, and does exactly what I want it to do for the scope of my program.
try {
if ((isNaN(errorhandle3) == true) || (isNaN(errorhandle2) == true)) {
throw "Error1";
}
} catch (e) {
if (e == "Error1") {
alert("Error! You must enter a number into the qty and cost fields!");
}
}
What I'm trying to accomplish with the try...catch block is simply to make sure that
document.myForm.Item_Code.value
document.myForm.Item_Cost.value
document.myForm.Quantity.value
are actually numbers.
The try...catch statements trigger every time I run the program and doesn't care what I put in the corresponding text boxes. I would greatly appreciate any and all insight on this!
Also: I looked at both of these links and was unable to understand my problem.
javascript parseInt return NaN for empty string
http://www.w3schools.com/jsref/jsref_isnan.asp
Your root problem here is that isNaN() tests to see if the value is NaN. It does not test to see if a string is a proper number. It has some coercion rules to try to deal with strings, but that really isn't what it is designed for.
You can see ways to test if something can be parsed into a valid number here: Validate decimal numbers in JavaScript - IsNumeric()
It's worth reading the detail in the good answers there, but it boils down to something like this which is a bit more than you need, but is general purpose:
function isNumber(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
And, then there's no reason to use exceptions in your code, so you can just do this:
if (!isNumber(errorhandle3) || !(isNumber(errorhandle2)) {
alert("Error! You must enter a number into the qty and cost fields!");
}
Also, in your code, some .Value properties look like maybe they should be .value (lowercase).
In your first code block
var errorhandle2 = parseInt(document.myForm.Item_Cost.Value);
var errorhandle3 = parseInt(document.myForm.Quantity.Value);
You are using Value, which should be value, that's case-sensitive.
By the way, isNaN returns boolean, you don't have to compare with true

Javascript (and JSP) won't create table properly with if statement

So i'm using multiple if statements to draw data from a database based on the users search criteria.
What i'm struggling with is
if(request.getParameter("searchProperty")!= ""){
SearchStatement = "town_city = '" + request.getParameter("searchProperty") + "'";
if(request.getParameter("bedrooms") != "0"){
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'";
}
}
with the idea that this concatenates a string to use as a query in the database, and bring back the results the user is searching for (this is a property searching website). I thought i'd done the if statement correctly. From what i understand, from what i've put, if the user were to select 0 in bedrooms it should return ALL results, but instead it returns NONE (who wants a house without a bedroom..) Can somebody explain what's going wrong please?
here's where the SQL statement is built and input
MyProperties = bookSQL.executeQuery("SELECT * FROM PROPERTIES WHERE " + SearchStatement);
with the expected outcome being, for example
SELECT * FROM PROPERTIES WHERE Location = 'input' AND Bedrooms = 'value'
unless value = 0 where it should just be
SELECT * FROM PROPERTIES WHERE Location = 'input'
i think the problem is with this statement,
request.getParameter("bedrooms") != "0"
should be something like this ,
(!request.getParameter("bedrooms").isEmpty())
Remember you are comparing the strings
so if is "0"
if(request.getParameter("bedrooms").equals("0")){
return SearchStatement ;
}
else {
SearchStatement += " AND bedrooms = '" + request.getParameter("bedrooms") + "'"
}
Hope this helps!!

How to check if all divs are hidden with variable class in jQuery

I'm very new to javascript/jQuery so apologies if this is a very basic question.
I have a variable which uses Math.random to select one of 9 potential classes from an array, the classes are the same except with a different number 1-9 at the end. I want to use javascript to check if all elements with this class are hidden. I can get it to check if all divs are hidden when I actually specify the class, but am not sure how to do this with a variable or expression. Below is what I'm using at the moment, which only works when the div is specified.
if ($('div.item9:visible').length == 0)
I assumed something like this would do what I want, but it doesn't seem to work.
if ($(variable + ':visible').length == 0)
EDIT: if ($(variable + ':visible').length == 0) this does work, I had another div on the page with this class which I didn't realise and therefore there was always an unhidden element, thanks for the help everyone.
you can use the same variable in your class name which you have used to select a number from 1-9 for example
var x = Math.floor(Math.random() * (10 - 1) + 1);
this will generate a random integer between 1-10 then you can just add the x in the class name
like this
if ($('div.item'+x+':visible').length == 0)
Cheers !
try this:
var elements = [1,2,3,4,5,6,7,8,9];
function getRandomClassNumber(){
//will give you random index
var index = Math.floor((Math.random()*elements.length));
return (elements[index]);
}
$("#btnRandom").on("click",function(){
var classNumber = getRandomClassNumber();
if($(".item"+classNumber).is(":visible")){
alert("item" + classNumber + " is visible");
}else{
alert("item" + classNumber + " not visible");
}
});
working fiddle here: http://jsfiddle.net/6neFA/

Making a value plural (Greater than, Less than) in Javascript

I have the following code:
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole" + (total_click = 1 ? + ' time' + ((total_click > 1) ? 's ' : ' ') : ''));
return false;
});
});
I'm trying to have it output as such:
Clicked once: "I cheated 1 whole time."
Clicked more than once: "I cheated X whole times."
-- With an 's' at the end of "times".
The counter is working fine, it's just the last part making the "time" or "times" show up appropriately that I am having difficulty with.
Any ideas what I'm doing wrong?
Thanks!
Here is your problem: total_click = 1. Try changing it to total_click == 1. I don't see why you have that conditional in there however, as it won't work as you expect anyway. Try $("#counter").text("I cheated " + total_click + " whole time" + ((total_click == 1) ? ' ' : 's '));
You are not using the ternary operator correctly, and also assigning total_click to 1 instead of checking its value. I would suggest moving this to a function to simplify things.
function pluralize(singular, times) {
if (times == 1) return singular;
else return singular + 's';
}
Then change the string to
var text = "I cheated " + clicks + " whole " + pluralize("time", clicks);
Here's an example.
$(function(){
var total_click = 0;
$("#mapKey a.showKey").click(function(){
total_click = total_click + 1;
$("#counter").text("I cheated " + total_click + " whole " + (total_click == 1 ? "time" : "times");
return false;
});
});
It's okay to use suggested implementations for a trivial cases, however it will not scale for a bigger set of problems and will not work for multiple languages (or it will get ugly very fast).
With this in mind, I’ve created a very simple JavaScript library that can be used to pluralize words in almost any language. It transparently uses CLDR database for multiple locales. It’s API is very minimalistic and integration is extremely simple. It’s called Numerous.
I’ve also written a small introduction article to it: «How to pluralize any word in different languages using JavaScript?».
Feel free to use it in your project. I will also be glad for your feedback on it!

Categories

Resources