<select name="" id="select">
<option value="01">地块一</option>
<option value="02">地块二</option>
<option value="03">地块三</option>
<option value="04">地块四</option>
<option value="05">地块五</option>
</select>
/***如何设置默认选中的选项***/
方法一: 标签属性: < option value = "01" selected = "selected" > 地块一 < /option>
jQuery: $( "#select option[value='" + val + "']" ).attr( "selected", true );
js: document.getElementById( "select" )[ 2 ].selected = true;
jQuery: $( "#select option[value='" + val + "']" ).attr( "selected", true );
js: document.getElementById( "select" )[ 2 ].selected = true;
/***如何获得选项option的值***/
方法一: var obj = document.getElementById( 'select' );
var index = obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[ index ].value;
方法二: var val = $( '#select' ).val()
/***如何获得选项option的文本***/
var obj = document.getElementById( 'select' );
var index = obj.selectedIndex; //序号,取当前选中选项的序号
var text = obj.options[ index ].text;
/***如何动态创建select***/
function createSelect() {
var mySelect = document.createElement( "select" );
mySelect.id = "mySelect";
document.body.appendChild( mySelect );
}
createSelect()
/***如何添加选项option***/
function addOption() {
var obj = document.getElementById( 'mySelect' ); //根据id查找对象,
obj.add( new Option( "文本", "值" ) ); //添加一个选项
}
addOption()
var obj = document.getElementById( 'mySelect' ); //根据id查找对象,
obj.add( new Option( "文本", "值" ) ); //添加一个选项
}
addOption()
/***如何删除所有选项option***/
function removeAll() {
var obj = document.getElementById( 'mySelect' );
obj.options.length = 0;
}
removeAll()
var obj = document.getElementById( 'mySelect' );
obj.options.length = 0;
}
removeAll()
/***如何删除一个选项option通过index***/
function removeOne() {
var obj = document.getElementById( 'mySelect' );
//index,要删除选项的序号,这里取当前选中选项的序号
var index = obj.selectedIndex;
obj.options.remove( index );
}
removeOne()
var obj = document.getElementById( 'mySelect' );
//index,要删除选项的序号,这里取当前选中选项的序号
var index = obj.selectedIndex;
obj.options.remove( index );
}
removeOne()
/***如何修改选项option***/
var obj = document.getElementById( 'mySelect' );
var index = obj.selectedIndex; //序号,取当前选中选项的序号
var val = obj.options[ index ] = new Option( "新文本", "新值" );
/***如何删除select***/
function removeSelect() {
var mySelect = document.getElementById( "mySelect" );
mySelect.parentNode.removeChild( mySelect );
}
removeSelect()
var mySelect = document.getElementById( "mySelect" );
mySelect.parentNode.removeChild( mySelect );
}
removeSelect()