简体   繁体   English

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

[英]Programmatically set select (multiple) element value

I want to populate a select field with onclick but i don't know how to filter the array to only the value of the clicked button. 我想用onclick填充选择字段,但是我不知道如何将数组过滤为仅单击按钮的值。 With my code all the array objects populate the input and I want only the value of the clicked button to populate the input. 使用我的代码,所有数组对象都将填充输入,而我只希望单击按钮的值来填充输入。 Any hints? 有什么提示吗?

<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>

I'll add a prefix to button id and set jQuery listener to it: 我将在按钮id前面添加一个前缀,并将jQuery侦听器设置为它:

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

So, the button will be: 因此,该按钮将是:

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

UPD : Code above is fixed, see it in action . UPD :上面的代码是固定的, 请参见实际操作 And I highly recommend to change value attribute on button to data-value , read more about data-* attributes 并且我强烈建议将按钮上的value属性更改为data-value了解有关data- *属性的更多信息

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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