通过javascript更改django中的select选项

时间:2021-11-24 02:06:17

I have the following issue :

我有以下问题:

1/ Using Django, I am generating a form containing a set of countries.

1 .我使用Django生成一个包含一组国家的表单。

The form is as follows :

表格如下:

country=forms.CharField(max_length=20
                     , widget=forms.Select(choices=countries)
                     , label=_('Country'))

The generated html is as follows

生成的html如下所示

<div class="form-group">
   <label class="col-lg-1" for="id_country"> … </label>
   <div class="col-lg-1">
      <select id="id_country" class="chzn-done" name="country" style="display: none;"> … </select>
      <div id="id_country_chzn" class="chzn-container chzn-container-single" style="width: 291px;" title=""> 
   </div>
</div>
</div>

2- I'd like to update the select dynamically using javascript

2-我想用javascript动态更新select

The code to update the select is provided below. The option is correctly changed. However, the "id_country_chzn" is not changed. The consequence is that although the option is changed, the value displayed for the end user is not changed. Is there a special trigger required ?

下面提供了更新select的代码。选项被正确地更改。但是,“id_country_chzn”没有更改。其结果是,虽然选项已经更改,但为最终用户显示的值没有更改。是否需要特殊的触发器?

The javascript code to update the option in the select is provided below. Could someone help me if I am missing anything ?

下面提供了在select中更新选项的javascript代码。如果我缺了什么,谁能帮我一下吗?

town.val('14').trigger('change');

Thanks a lot for your help

非常感谢你的帮助

1 个解决方案

#1


1  

When you manually change select value, you need to trigger the changes as well:

当您手动更改select值时,还需要触发更改:

$("#id_country").trigger("chosen:updated");

http://harvesthq.github.io/chosen/#change-update-events

http://harvesthq.github.io/chosen/ change-update-events

#1


1  

When you manually change select value, you need to trigger the changes as well:

当您手动更改select值时,还需要触发更改:

$("#id_country").trigger("chosen:updated");

http://harvesthq.github.io/chosen/#change-update-events

http://harvesthq.github.io/chosen/ change-update-events