select設置選中項/select的級聯


一、selected="selected"

HTML通過<select>的屬性來設置選中項,

此方法也可以在動態語言在后台根據需要控制輸出結果。

<select ID='sel' class="form-control width150">  
 <option value="1">開啟</option>  
<option selected="selected" value="0">關閉</option>   <!-- selected="selected" 默認選擇 -->
</select>

 

二、js來設置選中項:修改selected屬性值

<script >
var  ss = document.getElementById('sel');
ss[0].selected = true;//選中
</script>

 

三、jquery設置選中項- 設置指定value為項中

  1.設置value為vxx的項選中

   $(".selector").val("vxx");

     如:   $("#sel").eq(0).val("0");    

 

 

四、jquery設置選中項- 設置指定text為項中  

1.設置text為txx的項選中

    $(".selector").find("option:contains('pxx')").attr("selected",true);

1   $(".select").eq(0).find("option:contains('關閉')").attr("selected", true);
2             var opt = $(".select").eq(0).find("option:contains('關閉')");
3             console.log(opt);                         //obj {...}
4             console.log(    opt.attr("selected"));  // selected

第四行 顯示結果——

 selected

 

  2.注意:

  $(".selector").find("option[text='pxx']").attr("selected",true); 不可行

1   var opt = $(".select").eq(0).find("option[text='關閉']");
2    console.log(opt);                                      //obj{...}
3    console.log(    opt.attr("selected"));            // undefined

第三行顯示結果——

undefined

 

3、注意:獲取當前選中項的value

    $(".selector").val();

4、注意:獲取當前選中項的text

    $(".selector").find("option:selected").text();

 

五、select的級聯

即第二個select(obj2)的值隨着第一個select(obj1)選中的值變化,第三個第四個等其他select(other)也跟着變化

function GetChildrenData(dataobj, obj1, obj2,  other) {
    obj1.change(function () {

        var obj2Text = obj2.find("option").eq(0).text(); //請選擇...
        obj2.empty();
        obj2.append('<option value="">' + obj2Text + '</option>');
     

        if(other !=null )
        for (var i = 0; i < other.length; i++) {
            var otherText = other[i].find("option").eq(0).text(); //請選擇...
            other[i].empty();
            other[i].append('<option value="">' + otherText + '</option>');
        }
        if ($(this).val() != "") {
            dataobj.GetChildredData($(this).val(), function (re) {
                try {
                    var ds = JSON.parse(re.value).Table;
                    for (var i = 0; i < ds.length; i++) {
                        obj2.append('<option value="' + ds[i].ID + '">' + ds[i].Name + '</option>');
                    }
                } catch (e) { }
            })
        }
    })
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM