Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

problems when receiving form array with only one element in javascript

I am receiving a html form. This works fine when 2 or more elements in array, but when only one element is received I get error users[t] is null in fireBug?

var users = form.elements["uname[]"];

for(t in users) {
  dataString += "User: "+users[t].value+"\n"
}

this solved it:

if( typeof users.value === 'string' ) {
   users = [ users ];
}
like image 654
havheg Avatar asked Jan 18 '26 21:01

havheg


1 Answers

I know this is an old question but I stumbed across it while searching for something else. Anyway, I thought I'd provide another answer for anyone else who stumbled across this.

Rather than checking the type to see if it is an array or not and then optionally encasing the value in a new array, you can use Array.prototype.concat().

Its syntax is

var new_array = old_array.concat(value1[, value2[, ...[, valueN]]])

where any of those values can be either an array or a single value.

In your specific case, you can start with an empty array and concatenate your form input, which will work whether you get a single value or an array:

var users = [].concat(form.elements["uname[]"]);

or

users = [].concat(users);
like image 122
Richard Pickett Avatar answered Jan 21 '26 10:01

Richard Pickett