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

托罗斯塔

我想用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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

如何使用JavaScript以编程方式设置选择框元素的值?

以编程方式设置时间选择器值

以编程方式设置角度材料日期选择器值

以编程方式设置值按钮

以编程方式设置颜色选择器设置值时如何避免触发 Onchange 事件

以编程方式设置垫选择默认选项

熊猫:以编程方式选择多个列

Android以编程方式设置多个方向

在Internet Explorer中,如何以编程方式更改“选择”元素的(显示)值?

如何通过引用在 React 中以编程方式设置选择的值?

以编程方式设置Drupal节点选择列表字段值

以编程方式选择组合框值

Android如何在Kotlin中以编程方式设置多个重力值?

如何以编程方式为 Select 字段类型设置多个选定值?

jqGrid以编程方式设置filterToolbar值

以编程方式设置jsoup解析的网页的值

以编程方式设置<mat-select>的值

SwiftUI:以编程方式为Picker设置值

如何以编程方式设置DropdownButton的值?

如何设置选择多个值?

AlpacaJS:选择“选择”后以编程方式更改TextField的值

设置选择元素angularJS的选择值

以编程方式在可内容编辑的HTML元素中选择文本?

设置按钮选择器以编程方式发出

如何在TBCEditor中以编程方式设置文本选择?

在showOpenDialogSync中以编程方式设置项目选择

如何以编程方式设置在角度js中选择?

以编程方式设置在填充json之后选择的dropdownlist

如何以编程方式更改“选择时打开属性”设置?