Is there anything wrong with this statement? (Javascript) - javascript

I would like to know if there is anything wrong with the below statement.
document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value
Am asking this because, sometimes it seems to work fine and the rest of the time, it throws up an error - Object doesn't support this property or method.
BTW, monthId is the clientID of the dropdown present in a gridview in an asp.net page.
Thanks!

If no value is selected in the dropdown list, selectedIndex would be -1.

It's hard to evaluate without some more code as context. But without sanity checks around this line of code I would expect it to fail with an index out of bounds type exception when there is no selected index.

I tend to error check when using getElementById. I would expect that that is where your problem is.
Try this, and then test it in a debugger, but I will put an alert in.
var elem = document.getElementById(monthId);
if (elem.options) {
options[document.getElementById(monthId).selectedIndex].value
} else {
alert("elem doesn't have an options property");
}
You may want to not assume that the value property exists either, and do the same basic thing as I did here.
Once you get it working smoothly, where you know what is going to happen, you can start to remove the unneeded variables and go back to your original line, but for debugging, it is simpler to have one operation on each line and use separate variables, so that the debugger can show you what is happening.
You may want to understand the difference between undefined and null, and there are various pages on this topic but this one isn't too bad.
http://weblogs.asp.net/bleroy/archive/2005/02/15/Three-common-mistakes-in-JavaScript-2F00-EcmaScript.aspx

You can debug your problem by adding a breakpoint to your code in IE development tools, Firebug, Opera dragonfly or Chrome development tools and check your values.
Or you could add alert statements to check your values. Personally i think the code goes awry when selectedIndex is -1 (selectedIndex = -1 would occur when nothing is selected).
Check for yourself:
alert(document.getElementById(monthId)); // Returns null if nothing is found
alert(document.getElementById(monthId).selectedIndex); // If the selectedIndex is below 0 it could cause your error
document.getElementById(monthId).options[document.getElementById(monthId).selectedIndex].value

Related

how to make sure I dont get exception error or any kind of error in React that stop execution or crashes the app

When developing React app should we check every property if exists to make sure our app does not crash? I currently have for ex something like below:
<h3>{block && block.box && block.box.title}</h3>
but I wonder if I should do it like this:
<h3>{block && block.box && block.box.title && block.box.title}</h3>
to make sure block.box.title exists before accessing it!
Any idea how can i handle these things in javascript in general, this approach seems kinda verbose to me.
UPDATE, should this check be enough:
<h3>{block.box.title && block.box.title}</h3>
In this example, I think it's safe to assume that block exists, otherwise your code is probally incorrectly written, so that check isn't needed.
Then, the double title makes no sense. The syntax you're using (and most people) is a bit of a cheat, it effectivly does this:
isset(block) && isset(block.box) && echo(block.box.title)===true
This makes use of the fact that a string is considered true and that javascript parses from left to right.
It evaluates/runs the 1st part: run the ISSET, continue the checks if that's true
It evaluates/runs the 2nd part: run the ISSET, continue the checks if that's true
...
It evaluates/runs the last part: Echo the output, continue the checks if it's true.
At the last point, it has already output the string, then it evaluates the outcome. If the string hasn't been output (it's empty or it doesnt exists) that will return false.
Response to your update: No that wont work. It will try to access the title property of null if box doesn't exist, which results in an error,
New js feature here:
<h3>{block?.box?.title}</h3>

jQuery $.map works in IE8 but not IE7

Using jQuery 1.9.1 & IE8, but the page also needs to work in IE7. In code before the part that is causing the issue, I read some data in & build an array that is a SELECT statement. In the section of code where I have an issue, I am doing the following:
var found = $.map( mySelArr, function(val) {
return val.mySelID === zSelID ? val.mySelStatement: null;
});
I then reference it:
var selStmt = found[0];
(there will be only 1 returned, and I know it will be in the array).
In IE7, I saw that it is throwing an exception inside jquery.js. When I step through debug on it, I see that the found length is zero (in IE7). If I change the mode to IE8, everything works fine. But in IE7, nothing gets put into the found variable.
What am I doing wrong to not be able to get this array value out in IE7? Would appreciate any thoughts.
EDIT
mySelArr is an array of Select statements, similar to:
1,<select name='mySelID_1' id='plist' ><option selected='selected' disabled='disabled' value='0'>Select Action</option><option value="1">This one</option><option value="2">That one</option></select>
and so on.
EDIT 2
I may have stumbled on the issue.
The array that held the select statements was being populated correctly in IE8, but not in IE7.
I actually had 2 arrays, one being just a number, and the other being that same number + the Select statement. The array that had the index & select statement was built using:
arr1.push({ fld1:data1, fld2:selstmt})
The one with just numbers was built using:
arr2.push(arrndx)
The arr2 was the outer FOR, the arr1 was the inner FOR. I had been referring to the number index by using:
var z = arr2[x][0];
to get the number & then using that to loop thru arr1 to get everything matching it & building the Select statement. What I discovered was that IE7 was returning undefined in the line of code above, while IE8 was returning the number (Firefox also).
I changed 2 lines of code to fix the issue:
FROM arr2.push(arrndx)
TO arr2.push( {arrindex: arrndx} );
and
FROM arr2[x][0]
TO arr2[x].arrindex
and it works in both IE7 & IE8. IE7 didn't have a problem creating that array, or reading it - it just wasn't valid data in it because of how I attempted to reference the fields in it.
I'm not exactly sure why IE7 had a problem with it & IE8 didn't, but.... Also, the fix didn't appear to break anything else.

How do I debug in chrome to find out why this code doesn't work?

How do I use the JavaScript console to see why this code:
// Empty info
if ($('.perma-info').text() == '') {
$('.perma-info').remove();
}
Doesn't work in this page: http://dev-indiehaz.tumblr.com/post/22897976111/vans-vw
I want it so that if the element is empty, I can remove it.
You could start by:
console.log($('.perma-info'));
and then you observe the console. 2 possibilities: you get an empty resultset in which case you obviously should check your selector as there probably isn't an element with the class="perma-info" in your DOM or you get some result in which case you continue with:
console.log($('.perma-info').text());
and then observe the console. If you get an empty text then the if condition should work. If it prints some value then the DOM element that was matched had some text.
Happy debugging.
Press F12 and set a breakpoint.
Open up your Google Chrome Developement tool and click on Scripts
Select the correct script file and set the breakpoints you want (on the if-statement preferrably)
Start running the script!
Devtool will stop on the breakpoint. You can see global and local variables. You should store the text-value to a variable in order to see the actual content of the variable.
Follow others instructions to get to the dev tool but I think inside of your li there is a space. I use firebug on firefox and I saw a space.
try
if ( $.trim($('.perma-info').text()) == '') {
$('.perma-info').remove();
}

Javascript if statement refuse to load correctly from exterior script IE6 IE5.5

I see a very funny behaviour in my page when it comes to IE6 and IE5.5. I have a script (supersleight if you know about it) that puts PNG's back in business when dealing with IE6 and IE5.5. During execution of this, I want to change the background into using the Explorer alpha filter (if Javascript is turned on, use filter, otherwise stick to solid white).
I do this by:
if(document.getElementById('transparency') != null)
document.getElementById('transparency').style.filter= "alpha(opacity=60)";
...transparency is the id of the object in question.
Putting this at the end of the HTML page (or anywhere after 'transparency' was initiated) results in the script working. Putting it at the very end of the exterior script (deferred) however results in the filter NOT being applied.
However, when I remove the if statement and just tell the browser to use the filter it works (however only a few of the pages has got the 'transparency' id).
I tried to apply the if statement differently by using an alert box and trying both != null and == null and I get nothing.
This made me very curious so I tested this:
var tt = 5;
if(tt == 5)document.getElementById('transparency').style.filter= "alpha(opacity=60)";
Which gave an even stranger result with an error screen saying
tt is undefined
All of this runs perfectly in IE 7 and above...
I realize this is really two different issues but still...
Can anyone give me a clue as to what's going on?
Does this work?
var t = document.getElementById('transparency');
if (t && t.style) t.style.filter="alpha(opacity=60)";
How about this?
try {
document.getElementById('transparency').style.filter= "alpha(opacity=60)";
} catch (e) { }

Remove an arbitrary element from a JavaScript array

In my Google Maps application I can place markers on the map, and I keep a reference to each of the markers placed, along with some extra information in an array called markers.
Adding markers is easy, I just push() the newly created object onto the array (markers.push(marker));
However, when it comes to removing an arbitrary marker from the array, given an index of the slot, it doesn't behave as expected. My function is:
function deleteMarker(markerIndex) {
if (markerIndex!='' && markerIndex>=0 && markerIndex<markers.length) {
if (confirm('Do you really want to remove this marker from the map?')) {
alert('deleting marker '+markerIndex); //debugging purposes
markers.splice (markerIndex, 1);
}
}
}
I have no previous experience with the splice() function, but looking at its description # w3schools it seems to be pretty straight-forward. However, I get the following behaviour:
markers.splice() does nothing. So what am I doing wrong?
And also, when markerIndex is 0 no confirmation box is shown. At first I assumed the lengthy if-condition evaluated to false and so the whole code block was skipped, however, using Firebug to step through the calls I found out that the condition holds (of course) for index 0 when array is non-empty, next step reveals that the if (confirm(...)) and alert('deleting...) are skipped and markers.splice() is called (but nothing happens). This behaviour is so strange I decided to open this question.
Can anyone please clarify what's going on?
I thought that deleting markers will be the easiest bit of functionality one could do. I can add them, edit their contents, even clear all markers (pop()-ing markers off the markers array until empty) and all works nicely.
One problem with your code is that JavaScript interprets 0 == '' as true, so for a markerIndex of zero, your confirm-code is not executed. I guess that you misinterpreted the steps Firebug shows or that it simply is buggy here since your if-condition will in fact evaluate to false for a markerIndex of 0.
You can use type-strict comparison by adding an extra =:
if (markerIndex !== '' && ...) {
An easier approach would be:
if (markers[markerIndex] !== undefined) {
Since JavaScript does not raise an error when accessing undefined object members.
Your other problem with splice() not working is weird (it should work).
function deleteMarker(markerIndex) {
if (markers[markerIndex] !== undefined) {
if (confirm('Do you really want to remove this marker from the map?')) {
map.removeOverlay(markers[markerIndex]);
markers.splice (markerIndex, 1);
}
}
}
This seems to take care of all the problems. Thanks for your answers, much appreciated.
I especially like the idea of reducing the first if-condition to just:
if (markers[markerIndex] !== undefined)
splice() seems to operate directly on the array (contrary to what NuclearDog hinted) and it works as expected. My dearest Firebug mislead me.
not sure if this is what is happening here. but i've seen the same code run differently in firebug when it is being debugged v when it is not being debugged. i'm pretty sure i had no watches that were interfering with the code either.

Categories