把日常最常寫到的表單操作語法整理成一份速查表。
移除 option:
$("#ID option").each(function(){ if($(this).val() == 111){ $(this).remove(); } });
新增 option:
$("<option value='111'>UPS Ground</option>").appendTo($("#ID"));
取得選中項:
//取選中項的文字 $('#testSelect option:selected').text(); $("#testSelect").find('option:selected').text(); document.all.objSelect.options[document.all.objSelect.selectedIndex].text; //取得選中項的值 $("#testSelect").val(); //原生 JS document.getElementById('objSelect').value;
依值選中某項:
$('#testSelect').val('111'); document.getElementById('sel').value=objItemValue;
依索引選中(例如選第二項):
$('#select_id')[0].selectedIndex = 1;
$("input[type=radio][checked]").val(); //取得選中項的值 $(':radio[name="radio"]:checked').val();//另一種寫法 $("input[type=radio][value=2]").attr("checked",'checked'); //設定 value=2 為選中 $(':radio[value="2"]').attr('checked','checked');
依索引選中 radio 組的第二項:
$("input[name='items']").get(1).checked = true;
(其他寫法同 radio)
$("input[type='checkbox'][checked]").val(); //取得第一個選中項的值 $("#chk1").attr("checked",'');//取消勾選 $("#chk2").attr("checked",true);//勾選 //全選/取消全選 $("#selectAll").bind('click',function(){ var sa = $(this).attr("checked"); $("input[name='sel[]']").each(function(){ this.checked=sa; }); });
$(':input[name="keyword"]').val();//依 name 取值
固定尺寸、禁止使用者拖曳縮放:
<textarea name="123" style="resize:none;"></textarea>
版本提醒:在 jQuery 3.x 之後,.attr("checked") 的行為與早期版本不同,判斷與設定勾選狀態建議改用 .prop("checked", true/false),這也是這份寫法在現代專案中唯一需要調整的地方。