我想用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- *属性的更多信息
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句