need an expert view on my code javascript - javascript

I am doing a ternary operator check to see if a certain element is found on the document and set some style and property which will later modify based on other conditions related to user input.
but if the active page does not have those elements I don't want the javascript though error claiming "cant set disabled for null value".
so I use a ternary operator with an array to set multiple values for the element in the case it is found on the page.
my question is am I doing it right or there is a better way ???
submitCodeContent ? [
(submitCodeContent.disabled = true),
(submitCodeContent.style.backgroundColor = "#886A6C"),
]
: submitCodeContent;

Only use the conditional operator when you need to use the resulting expression. If you just want to perform operations if a particular condition is met, use if/else. Here, you just need
if (submitCodeContent) {
submitCodeContent.disabled = true;
submitCodeContent.style.backgroundColor = "#886A6C";
}
Using the conditional operator when you don't need the result is confusing to readers of the code, and should be avoided.

Related

How to check if NOT using Javascript bitwise operators?

I have a function that checks whether a user is premium by checking its flags:
isUserPremium() {
return this.flags & Flags.PREMIUM; // returns true
}
Now let's say that I'd want another function, but this time to check whether the user is free, but using the same flag. I tried negating the returned value, but I'd like to know if there was a better way to do this.
isUserFree() {
return !(this.flags & Flags.PREMIUM); // returns false
}
There isn't a way of checking whether a flag is not set with a single operator. I can suggest using !isUserPremium() instead of isUserFree() later in the code - don't create functions that invert a value returned from another function. However, make sure that you don't rely on this for security. Everything that is executing in the browser can be easily manipulated.

Array check element ID with wildcard in if statement

I can check an object ID in a array with
if (obj[0].id != "myID")
I would like to do the same with a wildcard, so that
if (obj[0].id != "myID*")
will exclude #myID1, #myID2, #myID3 etc.
I have to stay inside the if statement for this check, I can't call an external function.
If it is not possible, I can use obj[0].className instead of .id :
if (obj[0].className != "myClass")
but every object has several classes in addition of myClass.
jQuery is allowed although I'm not sure it will help.
If you're using jQuery (you've added the tag), why not use the selectors?
$('*:not[id^="myID"]')
This gets all the elements where the attribute does not start with myID. You can use this in your if statement like so:
if($(obj[0]).is('[id^="myID"]'))
First of all, you can definitely use an id attribute selector like this
if(!$(obj[0]).is("[id^=myID]"))
However, why not assign a class to all those elements instead? That sounds like a much more reasonable approach, allowing
if(!$(obj[0]).hasClass("myClass"))
Using String.prototype.indexOf might be one possible approach:
if (obj[0].id.indexOf('myID') !== 0) {
// ID does not start with 'myID'
}
You can even use regular expressions:
if( !/(myId)/g.test( obj[0].id.indexOf('myID') ) ) {
}
I can suggest you this really good playground to test you regexp:
http://lea.verou.me/regexplained/
And this talk:
http://www.youtube.com/watch?v=EkluES9Rvak
Regular expression can be very powerful. Maybe your case is not that hard to be managed with other tecniques but you would find regular expressions reeeally useful in the future for other problems.
You could check that the first 4 characters are myID with .substring():
if(obj[0].id.substring(0,4) != 'myId'){ }
If you wanted to use jQuery it would be really easy to check the id or class:
if(!$(obj[0]).is('[id^=myId]')){ }
or
if(!$(obj[0]).hasClass('myClass')){ }

Default Value in drop down list not being selected

I have a drop down list [ Incident, Question, Problem, Task]. I have written a code when an end user logins in and has a tag called product the default value should be problem. However it does not seem to work. It still gives the user the option to select values from the list.
$j(document).ready(function() {
if(location.pathname == '/requests/new') {
var ct = currentUser.tags;
if(ct.indexOf("product") >= 0){
$j(document.getElementById("ticket_fields_75389").value = "Problem");
}
else {
$j(document.getElementById("ticket_fields_75389").value = "");
}
}
})
Note: This answer is incorrect. I will delete it once I know the OP read my comment.
It still gives the user the option to select values from the list.
Well, of course, setting value will only change the initially selected value. If you want "fix" the value of the select element, so that the user cannot change it, you have to make it read-only. Lets stick with jQuery (what you have is a weird mix of DOM API and jQuery †):
$j("#ticket_fields_75389").val("Problem").prop('readonly', true);
†: Let's have a close look at the line
$j(document.getElementById("ticket_fields_75389").value = "Problem");
What exactly is happening here? Obviously we have a function call ($j(...)) and we pass something to it. This "something" is the result of the expression
document.getElementById("ticket_fields_75389").value = "Problem"
This finds an element by ID and assigns the string "Problem" to the value property. This is an assignment expression. The result of an assignment expression is the assigned value, i.e. "Problem".
That is the value that is passed to $j(...), so we have $j("Problem");. Since $j refers to jQuery, this would search for all elements with tag name Problem, which does not exist in HTML. It would also return a jQuery object, but you are not doing anything with it.
Hence the wrapping in $j(...) is completely unnecessary or even wrong, even though it doesn't throw a syntax or runtime error.

Evaluate string as a conditional statement

I am working on a c++ web-based IDE for beginners where one of it's core function is to let the user know the evaluation result (true or false) of the conditional statement they have on my contenteditable div.
Say i am already able to fetch the "fragment" (what i call it based on my architecture) that i wanted to evaluate and i already know the values of the variables...
Can you please suggest a way on how would i evaluate the text on the fragment as a conditional statement that will return either true or false...
Example
when var b = 5;
$('.frag').eq(1).text() //"if( (b>1) || (b==10) )"
after evaluation(what im asking for help) should return true
$('.frag').eq(2).text() //"(b>1)"
should return true
**$('.frag').eq(3).text() //"(b==10)"
should return false
UPDATE
The problem i am seeing with eval is that if i have a var1 in the contenteditable div and i have a var1 in my code. I should put a header on the variables from the contenteditable then right? like sc_var1 to prevent messing up with var1 from my source code?
You can use Eval like this:
var expression = $('.frag').eq(1).text();
var result = eval(expression);
However I generally do not recommend using eval because there is always a much better workaround.
if I get the bigger picture of your needs I would be able to provide a better solution.

Strange Javascript statement

if (1) {
google_conversion_value = 1;
}
What is the meaning of the above statement? I mean, this looks like it will always execute so why bother with the if statement?
updated: one reason might be remnants of scripting on the server side. Any other ideas?
updated2: could as easily change the value of the assignment without bothering with the if statement, no?
There are two likely explanations:
It's a leftover from debugging.
The file containing this code is generated dynamically and the original sourcecode contains something like if(<?php echo $some_stuff_enabled; ?>)
However, in the latter case it would have been cleaner to output that code block only if the condition is met - but maybe it's used in some crappy template engine that just allows replacements but no conditionals...
I've seen this before, and I've always assumed it was a remnant of some old condition that was no longer needed, but never removed. I can't see any actual reason to do something like that otherwise.
Potentially because the person writing the code wanted an easy way to turn it off and on again, this is especially useful if there is a lot of code inside the block (not the case here).
Another possibility is that the original programmer couldn't be bothered writing the logic or, more likely, it hadn't been specified so the "if" was left as a placeholder.
More than likely left in from a debug release or something similar. You're right, it will always execute. It could also have been done like this so that it can be easily enabled / disabled by setting the if to 0. Perhaps the developer intended to use it as a flag somewhere else in the code?
actually, this happens when the "if" condition is driven from server, so instead of doing the right thing and not produce the script when the condition is false, they do something like this:
if (<% if (my_server_condition) then Response.Write("1") else Response.Write("0") %>){
// code goes here
}
Perhaps the if statement used to check for a legitimate conditional, and then someone replaced it with a truthy value for testing/debugging/etc.
You're right, it will always execute because 1 is truthy. I would go through your source control history and investigate that line to see if it used to contain a real conditional. If the conditional was always 1, then it's likely a debugging statement. Otherwise someone might have meant for it to be a temporary change, and may not have meant to check that in (which could be bad).
I'm not sure where this code is from, but as you indicated it will always execute. As for why you'd do this, there are times where you want to see what the result of branch code would be, without having to setup an environment. In this case you can comment out the actual value and replace it with if(1) instead for testing:
// if( ... some hard to achieve condition )
if (1) {
// Now you can see what happens if this value is set quickly
google_conversion_value = 1;
}
Of course the problem with this is that it's sometimes easy to forget to remove the if(1) and uncomment the proper condition.
This is actually the javascript recommended by Google on http://support.google.com/adwords/bin/answer.py?hl=en&answer=1722054#nocomments (click on Step 2 for the sample HTML)

Categories

Resources