Search code examples
jquerymongodbtornado

How do I make an HTML dropdown menu have a default selected option depending on info sent from Mongo document using jQuery?


Not sure if I phrased this question correctly. I have a form to edit documents from MongoDB (using Tornado templating). When they click Edit, they go to a page where the form is pre-populated. In the form I have:

{% for group in doc.groups %}
     <div class="groupMenu">
         <select name="gName0" id="groupDropDown">
              <option value="group1">Group 1</option>
              <option value="group2">Group 2</option>
              <option value="group3">Group 3</option>
         </select>
     </div>
{% end %}

I'm not very good with jQuery and wanted to ask how do you write a function so that when a person clicks on edit and goes to fill out the form, the drop down defaults are set to whatever group is for each drop down?

Hope I was able to explain myself correctly.

EDIT: I want selected="selected" to be on group1, group2, OR group3, depending on what the group is.


Solution

  • Using the {% if condition %}{% end %} template tags, you could do this:

    {% for group in doc.groups %}
         <div class="groupMenu">
             <select name="gName0" id="groupDropDown">
                  <option {% if group == 'group1' %}selected="selected"{% end %} value="group1">
                      Group 1
                  </option>
                  <option {% if group == 'group2' %}selected="selected"{% end %} value="group2">
                      Group 2
                  </option>
                  <option {% if group == 'group3' %}selected="selected"{% end %} value="group3">
                      Group 3
                  </option>
             </select>
         </div>
    {% end %}
    

    If you wanted to use jQuery to do this, you could put the value in a hidden input field:

    <input class="default_group" type="hidden" value="{% group %}" />
    

    And then you could grab that value in jQuery, and set the selected option:

    var group = $('input.default_group').val();
    $('option[value="'+ group +'"]').attr('selected', 'selected');​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​
    

    Here's the jsfiddle demonstrating this.