※checkbox和radio
尤於Web開發的checkbox和radio常常會用到,下面就寫一個判斷、取值的範例裡面有些方法還沒介紹到,後面還會再介紹
function displayCheckbox(){
var count = $("input[name='alphabeta']:checked").length;
alert('checkbox勾了' + count + '個!');
// alert($("input[name='alphabeta']:checked").val());
alert($("input[name='alphabeta']").eq(0).val());
alert($("input[name='alphabeta']:eq(0)").val());
var $alphabeta = $("input[name='alphabeta']");
for(var i=0; i<$alphabeta.length; i++){
if($alphabeta.get(i).checked == 1){
alert('是' + $alphabeta.get(i).value);
alert('是' + $("input[name='alphabeta']:eq(" + i +")").val());
}
}
}
function displayRadio(){
var count = $("input[name='zoo']:checked").length;
if(count != 0){
alert('選的是' + $("input[name='zoo']:checked").val());
} else {
alert('沒選radio!');
}
}
----------
<input type="checkbox" name="alphabeta" value="A" checked="checked">
<input type="checkbox" name="alphabeta" value="B">
<input type="checkbox" name="alphabeta" value="C">
<input type="radio" name="zoo" value="monkey" id="m">
<input type="radio" name="zoo" value="dog" id="d">
<input type="radio" name="zoo" value="pig" id="p">
<input type="button" value="checkCheckbox" onclick="displayCheckbox()">
<input type="button" value="checkRadio" onclick="displayRadio()">
※註解那一行只會取到第一筆,radio的name一樣只會取到一筆,所以可以用;但checkbox就不適合了
※寫法有很多種
※select
※select單選
$(function($) {
$('option').eq(2).prop('selected', 'selected');
$('option').eq(3).hide();
$('option').each(function(){
if($(this).is(':selected')){
alert($(this).text());
}
});
});
----------
<select>
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
※select多選
$('option').each(function(i){
if(i % 2 == 0){
$(this).prop('selected', 'selected');
// $(this).hide();
}
});
----------
<select multiple="multiple">
<option value="a">A</option>
<option value="b">B</option>
<option value="c">C</option>
<option value="d">D</option>
<option value="e">E</option>
</select>
沒有留言:
張貼留言