![](/img/trans.png)
[英]Programmatically select value in DropDown element with JavaScript in Lightswitch
[英]Programmatically set select (multiple) element value
我想用onclick填充選擇字段,但是我不知道如何將數組過濾為僅單擊按鈕的值。 使用我的代碼,所有數組對象都將填充輸入,而我只希望單擊按鈕的值來填充輸入。 有什么提示嗎?
<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 :上面的代碼是固定的, 請參見實際操作 。 並且我強烈建議將按鈕上的value
屬性更改為data-value
, 了解有關data- *屬性的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.