以编程方式设置 select(多个)元素值

Programmatically set select (multiple) element value

我想用 onclick 填充 select 字段,但我不知道如何将数组过滤为仅包含单击按钮的值。使用我的代码,所有数组对象都会填充输入,我只希望单击按钮的值填充输入。有什么提示吗?

<input type="hidden" id="id_user" value="{{user.id}}"> 
    <select id="id_entities" class="js-example-programmatic" style="width:100%" multiple="multiple">
    {% for teu in tagEntityUsers %}
        <option value="{{teu.entity_id}}" class="js-programmatic-set-val">{{teu.entity}}</option> 
    {% endfor %}
    </select>

 {% for teu in tagEntityUsers %}
  <tr>
    <td><a href="/entities/{{teu.entity_id}}/{{teu.entity.slug}}">{{teu.entity}}</a></td>
    <td><a href="{{ teu.user.get_absolute_url }}">{{teu.user}}</a></td>
    <td><button id ="{{teu.entity_id}}" class="js-programmatic-set-val" value="{{teu.entity_id}}" onclick="populate_box(this.id)">add entity</button></td>
  </tr>
  {% endfor %}

<script>
var $example = $(".js-example-programmatic");
var arr = $.map($('.js-programmatic-set-val'), function (el) { return el.value; });
function populate_box() {
    $example.val(this.arr).trigger("change"); }
</script>

我将为按钮 ID 添加前缀并为其设置 jQuery 侦听器:

$("button[id^='prefix_']").click(function(){
   value = $(this).attr('data-value');
   $('#id_entities option[value="' + value + '"]').prop("selected", true).change();
});

因此,按钮将是:

<button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" data-value="{{teu.entity_id}}">add entity</button>

UPD:上面的代码是固定的,see it in action. And I highly recommend to change value attribute on button to data-value, read more about data-* attributes