2015-09-26 38 views
1

我想用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> 

回答

1

我會監聽器添加一個前綴按鈕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:以上代碼是固定的,see it in action。單擊該按鈕時,我強烈建議來改變按鈕data-valuevalue屬性,read more about data-* attributes

+0

感謝dr.dimitru但不工作..後,我改變你的例子沒有任何反應 – Torostar

+0

莫非你'的console.log(值)在這行之後:'value = $(this).attr('value');',確保有一些正確的值 –

+0

如果我做了console.log(value)它爲每個點擊按鈕輸出正確的值控制檯..但沒有發生在輸入字段 – Torostar

相關問題