Forum Moderators: open
The DOM 0 referencing methods, as you have found, return an element if there is only one, and a collection if more:
Is there an is_array() type function for JS that I could use here?
Could just ask:
if( obj.constructor==Array) ..but you can't use that here, because what is returned (when multiple) is a collection not a native Javascript array.
Testing for obj[0] is a reasonable alternative is this case.
You could "normalise" as you step through:
if(!obj[0]) obj=[obj]; Now, you can carry on, treating every reference you get as a collection. Even though some are native arrays, it will all be the same for our purposes.
ALTERNATIVELY
You could use DOM 1 to do the initial referencing
// from this
var boxes = document.forms.myForm.checks;
if(!boxes[0]) boxes = [boxes]; // wrap in array, if single// to this
var boxes = document.getElementsByName("checks");
The DOM 1 collection methods always return a collection. This is even better, since it means that you can run your loop, even if there are no boxes at all (The first method requires an extra line for that)
Hope this code helps you.
<script>
var radiogroup=document.forms[0].portlet1;
// Code if many are there
for(var j = 0 ; j <radiogroup.length;j++) {
if(radiogroup[j].checked) {
itemchecked = true;
empIdVal=radiogroup[j].value;
// alert(empIdVal);
break;
}
}
// Code if one is there.....
if(radiogroup!= null && radiogroup.length == null){
//alert("came");
if(radiogroup.checked) {
itemchecked = true;
empIdVal=radiogroup.value;
// alert(empIdVal);
}
}
</script>
var x = document.blah.checkboxcontrol
if (!x[0]) x[0] = document.blah.checkboxcontrol
Firstly, this would have been easier (since x is already pointing there):
if(!x[0]) x[0]=x;
Perhaps it's clearer now.
Native Javascript of objects are "soft" - you can add or remove "members" at will.
The majority of the other objects you're likely to meet in browser scripting are at least "mushy". You can add "expando" properties to DOM elements (since v4 browsers).
(There is essentially no difference at all between members associated using numbers and members associated using strings, except that you can't associate by numbers using dot syntax)
var elm = document.getElementById("myelm");
elm[35] = "hello";
elm.cupOfTea = 42;
x[0] = x;
x is now a member of itself.
x is not an array (although arrays aren't that special)
I would either wrap the element in an array:
if(!x[0]) x=[x];
or avoid the whole problem entirely:
var x = document.getElementsByName("checkboxcontrol");