0

I have a huge HTML select list that has a bunch of options. Some of the options have a 'parent' attribute which I'm using to identify. Basically, when someone picks the parent dropdown, all of it's children populate a different dropdown. So I'm trying to place all of these objects into an array, remove them from the page and then call them when I need them.

This is all HTML code that I've taken from a site we're working with so they make it work somehow themselves (not sure how though). My thought was just to make an object and push the items into that object (with keys of 'id' and 'parent'). It doesn't seem to work the way I'm doing it though:

var location_array = new Object();

$('select[name="location"] option').each(function(){
    if($(this).attr('parent')){
        var obj = {
            id: $(this).attr('id')
            parent: $(this).attr('parent')
        }
        location_array.push(obj);           
    }
});

Any help would be greatly appreciated. I know this is probably pretty basic but I don't do this type of coding very often. Thanks for your help!

2
  • Is parent an attribute in HTML ? Commented Aug 23, 2013 at 7:36
  • @MuhammadTalhaAkbar, I'd never seen it but it was able to grab the attribute. Like I said, I copied the code from another page that has working code and I was able to use console.log to print out the 'parent' value on all of the options, so it works. Commented Aug 23, 2013 at 7:38

2 Answers 2

3

Change

var location_array = new Object();

to

var location_array = [];

Object has no method .push()

Sign up to request clarification or add additional context in comments.

Comments

0

You're using push, but location_array isn't an array, it's an object.

I would probably keep it an object (I've changed the name):

var parents = {}; // A better way to write `new Object()`

$('select[name="location"] option').each(function(){
  var parent = $(this).attr('parent');
  parents[this.id] = parent;
});

Now you have a map, mapping element IDs to their parents. (Note that $(this).attr("id") is just a really roundabout way of writing this.id.)


Side note: When using custom attributes, stick with the data-* prefix to avoid conflicts with HTML-defined attributes (now and in the future).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.