DIV CSS 佈局教程網

jQuery 操作下拉、單選、核選三大控件速查
編輯:JQuery特效代碼     

表單三兄弟的操作語法整理成一份速查表,開發時直接對照。

Radio 單選鈕

<input type="radio" name="rd" id="rd1" checked="checked" value="rd1" />
<input type="radio" name="rd" id="rd2" value="rd2" />

// 取值(三種寫法皆可)
$('input:radio:checked').val();
$("input[type='radio']:checked").val();
$("input[name='rd']:checked").val();

// 設定選中
$('input:radio:first').attr('checked', 'checked');
$('input:radio').eq(索引值).attr('checked', 'true');
$('input:radio').slice(1, 2).attr('checked', 'true');
$("input:radio[value='rd2']").attr('checked', 'true');

// 刪除與遍歷
$("input:radio[value='rd2']").remove();
$("input:radio").eq(2).remove();
$('input:radio').each(function (index, domEle) { /* ... */ });

下拉選單 Select

// 取值
$('select#sel option:selected').val();
$('select#sel').find('option:selected').text();
$('select#sel').get(0).selectedIndex;          // 目前索引
$('select#sel')[0].options.length;             // 選項數量

// 設定選中
$('select#sel option:first').attr('selected', 'true');
$('select#sel')[0].selectedIndex = 索引值;
$("select#sel option[value='4']").attr('selected', 'true');

// 增刪
$("select#sel").append("<option value='6'>f</option>");
$("select#sel").prepend("<option value='0'>0</option>");
$("select#sel option[value='3']").remove();
$("select#sel option:first").remove();
$("select#sel option:last").remove();

核選框 Checkbox

// 單選取值
$("input:checkbox:checked").val();

// 多選取值
$('input:checkbox').each(function () {
  if ($(this).attr('checked') == true) { alert($(this).val()); }
});

// 全選與全不選
$('input:checkbox').each(function () { $(this).attr('checked', true); });
$('input:checkbox').each(function () { $(this).attr('checked', false); });

// 依 value 或索引設定
$("input:checkbox[value='1']").attr('checked', 'true');
$('input:checkbox').eq(索引值).attr('checked', 'true');

一定要知道的版本差異

以上 attr("checked") 的寫法來自 jQuery 1.x 時代。從 1.6 起,勾選狀態屬於「財產屬性」,請改用 .prop("checked", true) 設定、.prop("checked") 讀取;attr 只負責 HTML 初始屬性。另外 $('select#sel').attr('value','4') 在部分版本並不會真的改選中項,改成 $('select#sel').val('4') 才是可靠寫法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved