I have the following situation:
var answer = 'three';
var isClosed = true;
var condition = "answer != null && !isClosed";
The condition is a literal string and it's dynamically set by the user. Once they set the condition, I need to evaluate it inside an IF/ELSE sentence:
if(condition)
//Do something
else
//Do something
Can I do that without using "eval()"? How? I want to avoid it:
if(eval(condition))
...
NOTE: This is a simple example, the real situation is a bit complex with dynamic conditions :)
If you want to evade eval at all cost (as it can be really dangerous for the security reasons), you basically need a rules engine adapted to your dsl that you get from the database.
I googled this one and it seems prety decent C2FO , didn't actually tried it, but now you know where to start.
A bit confused..
But if the answer and isClosed set by the user.. then just something like this will suffice..
answer = null
isClosed = false // the default value for isClosed
if(answer != null && !isClosed){
//Do something
}
else{
//Do something
}
Related
everyone!
I have been having problems with my code. I think I know what is wrong but I can't seem to fix it, no matter how much I tried so I decided to take it up with the community. I think it is because of the second if statements contradict the one before it. Here, take a look.
if (Character.style.backgroundImage === "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/2.png)";
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
Hopefully, you see what I am talking about and know what the answer is. As I said in my last post I am not a great coder, so don't judge me too hard, XD.
There is no reason to repeat the conditional check negated with an else, that is only needed for an else if. Change
} else (Character.style.backgroundImage != "url(../images/animations/moveRightAnimation/1.png)") {
Character.style.backgroundImage = "url(../images/animations/moveRightAnimation/1.png)";
}
to something like
} else {
Character.style.backgroundImage =
"url(../images/animations/moveRightAnimation/1.png)";
}
Else doesn't take any parameters it's literally what runs in the case the if evaluates false.
If you want multiple exclusive if blocks, you need to use 'else if' where you currently have else
Syntax for if condition :
if ( condition ){
// code
}
else {
// code
}
Note : After else there cant't be any condition . Or you must use if-else.(Only if you want to use multiple conditions.And you seem to check only one,so its not needed.)
Syntax for if condition :
if ( condition ){
// code
}
else if ( condition ){
// code
}
First time writing Javascript. I just would like know if there is a shorter way of writing this:
<p id="demo"></p>
<script>
function myFunction() {
var letter = document.getElementById("myInput").value;
var text;
if (letter === "5544") {
text = "Abar, Marlon 1,800";
} else if (letter === "5545") {
text = "Pia, Darla 1,800";
} else if (letter === "5546") {
text = "Salazar, Alex 1,500";
//etc...
} else {
text = "Incorrect Account Number";
}
document.getElementById("demo").innerHTML = text;
}
</script>
Tried map but I couldn't get it to work.
There isn't really a shorter way to write an if statement in that way (which I will assume is what you're asking). However, there could be a few different ways to write this depending on how many things you want to check.
Use a Switch statement
There is a cleaner way when dealing with multiple cases that letter could be.
This would be a switch statement and it would look like this:
var text;
switch (letter) {
case "5544":
text = "Abar, Marlon 1,800";
break;
case "5545":
text = "Pia, Darla 1,800";
break;
// more cases
default:
text = "Incorrect Account Number";
break;
}
This reads a little better than an if else statement in some cases. The default keyword here acts as your else clause in an if else statement. The case acts as your different if statements if you will.
Essentially, the switch statement above will fall through each of the cases it defines until it finds a case that matches letter (such as "5544"). If none matches, it hits the default case. The break keyword at the end of each case stops things from falling through to the next defined case once a match is found.
This method could get cumbersome with more than 6 or 7 cases.
Create an object and look up the value
Now, a shorter way to get the value you want could be to define an object and get the value based on what has been entered like so:
var letter = document.getElementById('selector').value;
var obj = {
'5544': 'Abar, Marlon 1,800'
};
if (letter in obj) {
// do something if found
}
else {
// do something if not found
}
This could be an easy way to get a value if you have many values to check.
Other thoughts
As a side note to all of this, there are short hand if statements called ternary statements which you can find here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator ... However, I would not recommend nesting these as it becomes very complicated and not very readable.
Conclusion
So, to reiterate the answer to your question: No, there isn't really a shorter way to write an if else statement with many values. You can use a switch statement to make it cleaner. Use the object lookup method if you have many values you would like to check.
JavaScript has object (map) literals. Use them for terse code. In your final application you'll get the data for the map from someplace else and not code it directly into your website, but if you did, it would look like this:
document.getElementById( "demo" ).innerHTML = {
"5544" : "Abar, Marlon 1,800",
"5445" : "Pia, Darla 1,800",
...
}[ document.getElementById( "myInput" ).value ];
you can use switch for a long if - else -if ladder:
switch(expression) {
case n:
code block
break;
case n:
code block
break;
default:
default code block
}
This is how it works:
1)The switch expression is evaluated once.
2)The value of the expression is compared with the values of each case.
3)If there is a match, the associated block of code is executed.
if you need basic tutorials in java script then you should try w3 schools.
I have a section of a form that can be duplicated indefinitely, and I'm attempting to create a validation condition for it (using the ajaxForm plugin, although this aspect is relatively incidental).
The condition looks a bit like this:
if(formData[i].name == 'create-flight[fields][0][scheduled-departure-time]' && formData[i].value == ''){
// Do stuff
}
Note the 0 in create-flight[fields][0][scheduled-departure-time]. This could be a 0, a 1, or even a 37. Importantly I don't need to know, as the function handles everything dynamically and this condition triggers within a foreach, so every field will be checked. Is there a way to add a wildcard here? i.e. create-flight[fields]['+any_integer+'][scheduled-departure-time] ?
Often this would be catered for with an or operator, but it could be any number, so that's not practical.
Have you tried a regex? Try
formData[i].name.match(/^create-flight\[fields\]\[[0-9]+\]\[scheduled-departure-time\]$/)
I suggest you to use regular expressions (http://www.w3schools.com/jsref/jsref_obj_regexp.asp).
I would use something like:
/create-flight\[fields\]\[\d+\]\[scheduled-departure-time\]/
So the final code should look like this:
var patt = new RegExp(/create-flight\[fields\]\[\d+\]\[scheduled-departure-time\]/);
if(patt.test(formData[i].name) && formData[i].value == ''){
// Do stuff
}
You can test this with a regular expression:
var re = new RegExp("^create-flight\[fields\]\[[0-9]+\]\[scheduled-departure-time\]$");
if (re.test(formData[i].name)) {
// ...
}
Let me explain in more detail, I'm making a little sketch for my maths teacher that will calculate the missing sides and angles of a triangle. I have if/else/else if statements but I want an else if statement that will output something like "Check spelling" if none of the other statements are true. Basically, I want something that would do something like this (keep in mind I don't know how to program this yet)
// More code above
else if (side != "hypotenuse and adjacent"; "hypotenuse and opposite"; "opposite and adjacent") {
confirm("Please check spelling.");
}
Can you see what I am trying to do? A previous variable is called side and it prompts the user to input which sides of the triangle they have, so the sketch can work out the angle. What if they have a spelling mistake and it doesn't match any of the parameters I set, how would I make it follow out this block of code if they don't match? I may have just over-complicated things here but if someone could tell me how to do this, it would be greatly appreciated
You can try indexOf:
possibilities = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"]
// so if side not in that array (the same as not in any of that values)
if (possibilities.indexOf(side) == -1) {}
Are you asking for a default statement if none of the others are matched? Wouldn't that just be an normal else statement?
else{//what you want here}
The simplest way I can think of is to use if, else if and else. By using the else at the end, you won't need to write a huge check for the last line since all the previous.
if (A) { A is true }
else if (B) { Not A, but B }
else if (C) { Not A or B, but C }
else { Not A, B or C }
An much nicer way to do this trick, is to use a switch/case, which is described here.
switch(n) {
case A:
A is true
break;
case B:
B is true
break;
default:
Not A or B
}
However, if you only want the last check for "spell checking", I'd say #zishe has a neat answer to that.
The most simple way to do this is to use jQuery function:
$.inArray(value, array)
which returns either positive index if the string can be found inside of array or -1 otherwise. So the solutions should be something like this:
var myArray = ["hypotenuse and adjacent", "hypotenuse and opposite", "opposite and adjacent"];
// more code above
else if($.inarray(side, myArray) == -1) {
confirm("Please check spelling.");
}
I'm checking a number of 'read more' links on my blog, and either hiding the link (for the first two posts), or hiding the content and keeping the link. I'm running the links' id attributes through an if ... else statement that looks like so:
$(document).find('.contentclicker').each(function(){
var pt = $(this).parent().attr('id');
if (pt == "postnum1" || "postnum2"){
$(this).hide();
}
else{
$(this).next().hide();
}
});
Note: There's some jQuery in there, but it's not relevant. I know from debugging that the var pt is being set correctly to post_num_1, post_num_2, etc. - but when it evaluates post_num_3 and so on, it doesn't go to the else. I've tried == and ===, among other things, and I can't figure out what's wrong.
Any suggestions?
I am pretty sure you cannot do if (pt == "postnum1" || "postnum2") in javascript. Try if (pt == "postnum1" || pt == "postnum2"). Basically, even if the first conditional of pt == "postnum1" were false, it'd treat the second conditional as true which would avoid the else clause at the bottom. At least, that's what I think.
Sorry if I misunderstood your question.
JavaScript is not strictly typed, it means in particular that it gives you some leeway int your data types and always tries to coerce the expression value to the data type it thinks to be your intention.
In your if statement it tries co convert the part after || to boolean and result of conversion of "postnum2" is always true.
I think what you intended was (pt == "postnum1" || pt == "postnum2")
The second part of condition "postnum2" always evaluates to true. You have to convert condition to first answer. Also your post says post_num_1, post_num_2, etc, but you are checking for post_num1.
Instead of if (pt == "postnum1" || "postnum2")
try
if ((pt == "postnum1" ) || (pt == "postnum2"))
{
// something
}
Also you can do something in the switch case(as an alternative)
switch(pt)
{
case "postnum1":
case "postnum2" : $(this).hide(); break;
default: $(this).next().hide(); break;
}