简体   繁体   中英

Set default option in select element and load data

On my html-template I got a select-element looking like this:

<select class ="form-control", id="categories">
            {% for c in categories %}
                <option value = {{c.id_category}}>{{c}}</option>
            {% endfor %}
</select>

Where the user can choose one of the avaiable categories and with javascript the according database entries of that category get loaded in to a table on the site.

$(document).ready(function(){
   $("#categories").change(function(e){
...

The script only gets active when one uses the dropdown menu. At the moment if you first access the site no data will be shown by default. What I want it to do though is, that by default one of the categories (doesnt really matter which) is selected and the corresponding data is shown. If I simply use 'selected' for one of the options no data will be in the table (obviously, cause the JS doesnt register a change of a selected option). So how can I do this?

You can chain a call to trigger after your event handler to call it on page load

$(document).ready(function(){
  $("#categories").change(function(e) {
    ...
  }).trigger('change');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM