select
相关概念: option, selected, onChange(没有onSelect事件)
// html demo
<select name="cityCode">
<option value="021">上海</option>
<option value="0571" >杭州</option>
<option value="0576">台州</option>
</select>
相关操作:
// 1. 默认选中value为021的选项
// 方法一:html
<option value="0576" selected>台州</option>
// 方法二: jquery
$('select').val('021');
// 2. 默认选中text为上海的选项(检验无效)
$('select').find('option[text="上海"]').attr('selected', true)
// 3. 获取选中值
$('select').val();
// 4. 获取选中text
$('select').find('option:selected').text();
// 5. 动态删除选项
$('select').find('option[value="0576"]').remove();
// 6.动态添加选项
$('select').append('<option value="010">北京</option>');
// 7. select事件onchange
$(document).ready(function(){
$('select').on('change', function() {
alert($(this).val());
})
});
checkbox
相关概念: checked, onChange, onClick(没有onCheck事件)
<p>水果:</p>
<input type="checkbox" name="fru_1" value="orange">橘子</input>
<input type="checkbox" name="fru_1" value="apple">苹果</input>
<p>蔬菜:</p>
<input type="checkbox" name="veg_1" value="tomato">番茄</input>
<input type="checkbox" name="veg_1" value="potato">土豆</input>
// 1. 设置默认选中,根据value
// 方法一:html
<input type="checkbox" name="fru_1" value="orange" checked>橘子</input>
// 方法二:
$('input[name="fru_1"][value="orange"]').attr('checked', true);
// 方法三:索引
$('input[name="fru_1"]:first').attr('checked', true);
$('input[name="fru_1"]:last').attr('checked', true);
$('input[name="fru_1"]').eq(1).attr('checked', true);
// 2. 设置默认选中,根据text(检验无效)
$('input[name="fru_1"][text="苹果"]').attr('checked', true);
// 3. 获取选中值
var checkedElements = $('input[name="fru_1"]:checked');
alert("选中个数:" + checkedElements.length);
var valueArr = [];
$(checkedElements).each(function() {
valueArr.push($(this).val());
})
alert(valueArr);
// 4. checkbox事件change, click事件(对单个框)
$(document).ready(function(){
$('input[name="fru_1"]').on('change', function() {
// 判断是否选中
var checked = this.checked,
// 或者
// checked = $(this).is(':checked'),
// 获取值
value = $(this).val();
});
$('input[name="fru_1"]').on('click', function() {
// 获取值
alert($(this).val());
});
});
radio
相关概念: radio, checked, onChange, onClick
// html demo
<p>水果:</p>
<input type="radio" name="fru_1" value="orange" >橘子</input>
<input type="radio" name="fru_1" value="apple">苹果</input>
<p>蔬菜:</p>
<input type="radio" name="veg_1" value="tomato">番茄</input>
<input type="radio" name="veg_1" value="potato">土豆</input>
相关操作:参考checkbox