I'm trying to check a series of check boxes depending on the results I get from a string. Since the values in this string are separated by commas I do the following:
var busLines = 'AB, CD, EF, GH, IJ, KL'
var temp = busLines.split(', ');
So now my array 'temp' should be the individual elements of my string:
temp[0] = 'AB'
temp[1] = 'CD'
temp[2] = 'EF'
and etc...
Each one of those values that are being returned in my array of 'temp' correspond with a check box with the same ID. So when I loop through and value 'AB' comes up, the check box id='AB' will get checked.
That is why I try this:
for (var i = 0; i < temp.length; i++) {
document.getElementById(temp[i]).checked = true;
}
When I test it out id does exactly what I want it to do, but it gives me the following error:
Message: 'document.getElementById(...)' is null or not an object Line: 530 Char: 9
I don't understand why I am getting an error when what I want it to do works. Any suggestions?
3 Answers 3
Most likely you have an ID that wasn't found on the page. You should be coding this defensively anyway, by adding in null checks and such.
Try something like this:
for (var i = 0; i < temp.length; i++) {
var checkBox = document.getElementById(temp[i]);
if(checkBox) {
checkBox.checked = true;
}
}
3 Comments
That means one of your IDs doesn't exist (or possibly there's an extra "," at the end of your string. You should make sure all the IDs exist. If you just want to ignore the error, you can wrap your call to getElementById in a try/catch.
9 Comments
document.getElementById returning null is to be expected and handled properly by conditional checks. using exceptions and exception handlers for non-exceptional cases to control program flow is a bad practice in any language.try/catch around the outer loop handled all of them much simpler and more foolproof. I don't understand why exception handling in JS gets labeled as bad practice. It can be very, very useful and more foolproof in some cases.I think your loop is accessing one more item than really exists e.g. when busLines ends with ', '
busLines? What's intemp[i]? Do you have an element on your page that has an ID oftemp[i]? Please add all relevant info.new Array()is not useful. Just assign the result of the split directly.var temp = busLines.split(', ');