例:將多個選中的checkbox的值組裝成一個字符串html
<script type=text/javascript>
function addMem(){
//var followers = document.getElementsByName("followers");
var f_str = '0';
$("input[@name='followers']").each(function(){
if($(this).attr("checked")==true){
f_str += ","+$(this).attr("value");
}
})
alert(f_str);
}
</script>java
=====================jquery
例:取選中的radio的值web
var gender = $('input[@name=gender][@checked]').val();app
=====================this
轉別人的一些東西:spa
在html的checkbox裏,選中的話會有屬性checked="checked"。blog
若是用一個checkbox被選中,alert這個checkbox的屬性"checked"的值alert($"#xxx".attr("checked")),會打印出"true",而不是"checked"!
若是沒被選中,打印出的是"undefined"。以爲很奇怪是嗎?繼續看下去~
不要嘗試去作這樣的判斷:if($"#xxx".attr("checked")=="true")
由於這麼作是錯的,jQuery的API手冊上寫,attr(name)的返回值是object。
因此,應該是if($"#xxx".attr("checked")==true)
====================================
jquery全選/取消選擇checkbox示例:
<input type="checkbox" name="checkbox_name[]」 id=」checkbox_name_1″ />1<br />
<input type=」checkbox」 name=」checkbox_name[]」 id=」checkbox_name_2″ />2<br />
<input type=」checkbox」 name=」checkbox_name[]」 id=」checkbox_name_3″ />3<br />
<input type=」checkbox」 name=」checkbox_name[]」 id=」checkbox_name_4″ />4<br />
<input type=」checkbox」 name=」checkedAll」 id=」checkedAll」/>全選/取消全選
=================================================
獲取一組radio被選中項的值
var item = $('input[@name=items][@checked]').val();
獲取select被選中項的文本
var item = $("select[@name=items] option[@selected]").text();
select下拉框的第二個元素爲當前選中值
$('#select_id')[0].selectedIndex = 1;
radio單選組的第二個元素爲當前選中值
$('input[@name=items]').get(1).checked = true;
獲取值:
文本框,文本區域:$("#txt").attr("value");
多選框checkbox:$("#checkbox_id").attr("value");
單選組radio: $("input[@type=radio][@checked]").val();
下拉框select: $('#sel').val();
控制表單元素:
文本框,文本區域:$("#txt").attr("value",'');//清空內容
$("#txt").attr("value",'11');//填充內容
多選框checkbox: $("#chk1").attr("checked",'');//不打勾
$("#chk2").attr("checked",true);//打勾
if($("#chk1").attr('checked')==undefined) //判斷是否已經打勾
單選組radio: $("input[@type=radio]").attr("checked",'2');//設置value=2的項目爲當前選中項 下拉框select: $("#sel").attr("value",'-sel3');//設置value=-sel3的項目爲當前選中項 $("<option value='1'>1111</option><option value='2'>2222</option>").appendTo("#sel")//添加下拉框的option $("#sel").empty();//清空下拉框