0

How can I set the option value of a drop-down list to the option selected by the user. I believe I need to use a script but I am unsure as to the best practice. The options are populated via JSON response. This functionality is needed for form submission.


    <div class="select">
        <select name="selectcompanies" id="selectcompanies">
            <option value="">Company</option>
            {% for company in companies %}
                <option value="" name="selected_company" id="selected_company">{{ company.name }}</option>}
            {% endfor %}
        </select>
    </div>

Anshu
  • 1,277
  • 2
  • 13
  • 28
garmars
  • 129
  • 1
  • 12
  • Possible duplicate of [Set select option 'selected', by value](https://stackoverflow.com/questions/13343566/set-select-option-selected-by-value) – Tijkijiki Jun 10 '19 at 16:34

1 Answers1

0

To make a select option as "selected" we can use the "selected" html attribute.

While looping the json value,

  1. check the json value with the current option value
  2. if they match, set the selected attribute to that option value.

It will make that option appear as selected.

You can refer to https://www.w3schools.com/tags/att_option_selected.asp for more details.

Sinha
  • 512
  • 4
  • 11
  • I need to set the option value based on the option selected for form submission. So what I want is this: – garmars Jun 10 '19 at 14:48