本文實例講述了jquery操作select常見方法。分享給大家供大家參考,具體如下:
在前段HTML頁面設計中select 下拉框,或者 在 multiple="multiple" 時,表現為列表。經常會在頁面上對其進行操作,這些操作不外乎:
1. 得到選中的 select 的 option 的值或者text.
2. 刪除選中的 select 的 option.
3. 向select中增加新的option.
4. 得到select option 長度,也就是個數size
5. 清空select.
6. 兩個select 框之間互相添加刪除,從左邊到右邊,從右邊到左邊的操作,通常是多選情況。
7. 判斷在 select 框中是否存在某一個值的選項
對第一種情況,用如下方法:
$("#select_id").change(function(){//code...}); //為Select添加事件,當選擇其中一項時觸發var checkText=$("#select_id").find("option:selected").text(); //獲取Select選擇的Textvar checkValue=$("#select_id").val(); //獲取Select選擇的Valuevar checkIndex=$("#select_id ").get(0).selectedIndex; //獲取Select選擇的索引值var maxIndex=$("#select_id option:last").attr("index"); //獲取Select最大的索引值 jQuery設置Select選擇的Text和Value:
$("#select_id ").get(0).selectedIndex=1; //設置Select索引值為1的項選中$("#select_id ").val(4); //設置Select的Value值為4的項選中$("#select_id option[text='jQuery']").attr("selected", true); //設置Select的Text值為jQuery的項選中
對第二種情況,刪除的處理:
$("#select_id option:last").remove(); //刪除Select中索引值最大Option(最后一個)$("#select_id option[index='0']").remove(); //刪除Select中索引值為0的Option(第一個)$("#select_id option[value='3']").remove(); //刪除Select中Value='3'的Option$("#select_id option[text='4']").remove(); //刪除Select中Text='4'的Option
如果要刪除選中的option ,則需要先得到 選中option 的序號. var checkIndex=$("#select_id ").get(0).selectedIndex;
然后再調用上面的方法刪除.
對第三種情況,增加option 的處理:
$("#select_id").append("<option value='Value'>Text</option>"); //為Select追加一個Option(下拉項)$("#select_id").prepend("<option value='0'>請選擇</option>"); //為Select插入一個Option(第一個位置)
對第四種情況,得到select 的長度
var totalcount=$("#single_user_choice").get(0).options.length;
第五種情況,清空select
$("#single_user_choice").get(0).options.length=0;
第六種情況。兩個select 框之間互相添加刪除,從左邊到右邊,從右邊到左邊的操作,通常是多選情況,也就是設置了 multiple="multiple" 。
var $options = $('#select1 option:selected');//獲取當前選中的項var $remove = $options.remove();//刪除下拉列表中選中的項$remove.appendTo('#select2');//追加給對方
第七種情況,判斷在select 是否存在某個value 的 option
function is_Exists(selectid,value){ var theid='#'+selectid; var count=$(theid).get(0).options.length; var isExist = false; for(var i=0;i<count;i++){ if ($(theid).get(0).options[i].value == value){ isExist=true; break; } } return isExist;}
更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jQuery常見事件用法與技巧總結》、《jQuery常用插件及用法總結》、《jQuery操作json數據技巧匯總》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》及《jquery選擇器用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答