简体   繁体   English

jQuery:单击按钮后,选择下拉选项

[英]Jquery : On clicking the button select drop down option

I am jquery learner. 我是jquery学习者。

<select multiple id="update-select" data-type="test1, test2">
        <option value="3">test1</option>
        <option value="4">test2</option>
        <option value="5">test3 test</option>
        <option value="5">test test</option>
</select>

<input type="button" id ="btn" value ="click me">


$(document).ready(function() {
   $("#btn").click(function(){

   });   
});

jsfiddle here jsfiddle在这里

I am setting the data-type value dynamically based on some server data. 我正在基于某些服务器数据动态设置数据类型值。 on clicking the button option whose value equal to data-type value must be selected 单击按钮选项时必须选择其值等于数据类型值

Here data-type values are test1 and test2 so option test1 , and test2 must be selected on clicking the button 这里的数据类型值为test1test2因此必须在单击按钮时选择选项test1test2

Note: data-type values can have two word values like test test, option text also can have test test 注意:数据类型值可以有两个单词值,例如test test,选项文本也可以具有test test

$(document).ready(function() {
   $("#btn").on('click', function(){
       $('#update-select option').prop('selected', false);
       $.each($('#update-select').data('type').split(','), function(i, opt) {
           $('#update-select option:contains('+ $.trim(opt) +')').prop('selected', true);
       });
   });   
});

FIDDLE 小提琴

You can do like this: 您可以这样:

$(document).ready(function() {
    $("#btn").click(function(){
         $('#update-select option').prop('selected', false);
        var select = $("#update-select").attr('data-type').split(',');
        for(var i=0; i<select.length; i++){
           $('#update-select option:contains('+ $.trim(select[i]) +')').prop('selected', true);   
        }
    });   
});

check http://jsfiddle.net/alaminopu/V85Vx/23/ 检查http://jsfiddle.net/alaminopu/V85Vx/23/

Use .filter() function to get your target option tags and select it afterwards. 使用.filter()函数获取目标option标签,然后选择它。

$(document).ready(function() {
   $("#btn").click(function(){  

       var xText =$('#update-select').data('type');

       $('#update-select option').filter(function(){
           return xText.indexOf($(this).text()) != -1;   
       }).prop('selected', true);

   });   
});

DEMO 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM