Byron Smith
Byron Smith

Reputation: 607

javascript/jquery: creating a list of all option elements's text in a select tag

I'm working on the Django web development platform, so I use some of the django template languages in creating my menu. My task is simple, but it's been a while since I've worked with js and I'm not sure what I'm doing wrong right now

I just need to create a list of strings for each option element's text or the string for its value attribute. But right now, nothing seems to be getting iterated over...

The select tag

<div id="keywordCollection">
  <select id="#allKeywords">
   {% for keyword in keywords %}
   <option value="{{ keyword }}">{{ keyword }}</option>
   {% endfor %}
  </select>

Javascript (note that this is inline script in the HTML file for this web page and it appears immediately after the above.)

<script>
  var collection = []
  $("#allkeywords option").each( function() {
    //This never begins running.
    console.log("ADDING");
    collection.push($(this).value);
   });
  $(function(){
     var collection = [];
     var keywords = $("#allKeywords option");
     for(var i=0; i<keywords.length; i++) {
        // This doesn't ever begin running, keywords.length == 0.
        kw = keyword[i];
        console.log(kw);
    }
   $("#allKeywords option").each( function() {
    //this doesn't ever begin running. 
    collection.push($(this).value);
   });
  .... //irrelevant code that I cut out.
 });
</script>

So none of my loops ever begin. At this point, you might be wondering if my elements actually have anything in it... But yes it does. That django for-loop populates the menu and I can see it right on my page.

What am I missing here?

Upvotes: 0

Views: 52

Answers (1)

Guillaume Georges
Guillaume Georges

Reputation: 4020

Remove the '#' in the id parameter of your select tag :

<select id="allKeywords">
   {% for keyword in keywords %}
   <option value="{{ keyword }}">{{ keyword }}</option>
   {% endfor %}
</select>

That way, the selector below should work :

$("#allkeywords option").each( function() {
  // ...
}

Upvotes: 1

Related Questions