Alex Rivera | Logout

Pushing value of Var into an Array

Asked 2009-08-17T03:48:32.307
18

I know this is probably a simple question, but I'm attempting a tweak in a plugin & js is not my expertise and I got stumped on how to do the following:

I have an array that can contain a number of values ($fruit) depending on what a user has entered. I want to add another variable to the array that isn't determined by manual input.

I know push should apply here but it doesn't seem to work, why does the following syntax not work?

var veggies = "carrot";
var fruitvegbasket = $('#fruit').val();
fruitvegbasket.push(veggies);

update: I got it working doing this:

var fruit = $('#fruit').val();
var veggies = "carrot";
fruitvegbasket = new Array();
fruitvegbasket.push(fruit+","+veggies);

not sure that's the best way to do it, but it works. thanks all!

Edit
Report

2 Answers

1

.val() does not return an array from a DOM element: $('#fruit') is going to find the element in the document with an ID of #fruit and get its value (if it has a value).

answered 2009-08-17T03:53:51.267
0

Perhaps $('#fruit').val(); is not returning an array and you need something like:

$("#fruit").val() || []

http://docs.jquery.com/Attributes/val

answered 2009-08-17T03:57:30.870

Your Answer