我想使用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>
答案 0 :(得分:1)
我会在按钮ID中添加一个前缀,并为其设置jQuery监听器:
...
Rule(LinkExtractor(allow=(r'threads/\w+',)), callback='parse_thread', process_value=clean_url)
...
def clean_url(value):
value = value.replace(u'%0A', '')
value = value.replace(u'%09', '')
return value
所以,按钮将是:
$("button[id^='prefix_']").click(function(){
value = $(this).attr('data-value');
$('#id_entities option[value="' + value + '"]').prop("selected", true).change();
});
UPD :以上代码已修复see it in action。我强烈建议您将按钮上的<button id="prefix_{{teu.entity_id}}" class="js-programmatic-set-val" data-value="{{teu.entity_id}}">add entity</button>
属性更改为value
,read more about data-* attributes