jquery selectドロップダウンボックス選択コード

3812 ワード

<select name=’sel’ id=’sel’>
<option value=’1′>1</option>
<option value=’2′ selected=’selected’>     </option>
<option value=’3′>2</option>
</select>
<script>
alert($("select[@name='sel'] option[@selected]").text());
$("#sel").val(’2′);
alert($("select[@name='sel'] option[@selected]").text());
</script>

クエリーで選択するoptionの内容はもちろんalert($("#sel option[@selected])でもよい.text());
ちょっと説明します.
select[@name='sel']option[@selected]は、name属性を有し、この属性値が「sel」のselect要素の中のselected属性を有するoption要素を表す.@の先頭にあるのは後ろに付いているのが属性であることがわかります.
selectアイテムを取得する個数

jQuery.fn.size = function()
{
return jQuery(this).get(0).options.length;
}
//        
jQuery.fn.getSelectedIndex = function()
{
return jQuery(this).get(0).selectedIndex;
}
//          
jQuery.fn.getSelectedText = function()
{
if(this.size() == 0)
{
return "       ";
}
else
{
var index = this.getSelectedIndex();
return jQuery(this).get(0).options[index].text;
}
}
//         
jQuery.fn.getSelectedValue = function()
{
if(this.size() == 0)
{
return "        ";
}
else
{
return jQuery(this).val();
}
}
//  select   value     
jQuery.fn.setSelectedValue = function(value)
{
jQuery(this).get(0).value = value;
}
//  select    text       
jQuery.fn.setSelectedText = function(text)
{
var isExist = false;
var count = this.size();
for(var i=0;i<count;i++)
{
if(jQuery(this).get(0).options[i].text == text)
{
jQuery(this).get(0).options[i].selected = true;
isExist = true;
break;
}
}
if(!isExist)
{
alert("         ");
}
}
//         
jQuery.fn.setSelectedIndex = function(index)
{
var count = this.size();
if(index >= count || index < 0)
{
alert("         ");
}
else
{
jQuery(this).get(0).selectedIndex = index;
}
}
//  select        value  
jQuery.fn.isExistItem = function(value)
{
var isExist = false;
var count = this.size();
for(var i=0;i<count;i++)
{
if(jQuery(this).get(0).options[i].value == value)
{
isExist = true;
break;
}
}
return isExist;
}
// select     ,     text,  value,        ,   
jQuery.fn.addOption = function(text,value)
{
if(this.isExistItem(value))
{
alert("         ");
}
else
{
jQuery(this).get(0).options.add(new Option(text,value));
}
}
//  select   value  ,       ,   
jQuery.fn.removeItem = function(value)
{
if(this.isExistItem(value))
{
var count = this.size();
for(var i=0;i<count;i++)
{
if(jQuery(this).get(0).options[i].value == value)
{
jQuery(this).get(0).remove(i);
break;
}
}
}
else
{
alert("        !");
}
}
//  select       
jQuery.fn.removeIndex = function(index)
{
var count = this.size();
if(index >= count || index < 0)
{
alert("          ");
}
else
{
jQuery(this).get(0).remove(index);
}
}
//  select     
jQuery.fn.removeSelected = function()
{
var index = this.getSelectedIndex();
this.removeIndex(index);
}
//  select     
jQuery.fn.clearAll = function()
{
jQuery(this).get(0).options.length = 0; }