JQuery操作checkbox、radio等示例

xiaoxiao2026-10-08  1

例:将多个选中的checkbox的值组装成一个字符串

 

<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>  

 

=====================

例:取选中的radio的值

 

var gender = $('input[@name=gender][@checked]').val();  

=====================

转别人的一些东西:

jquery判断checkbox是否被选中

在html的checkbox里,选中的话会有属性checked="checked"。

如果用一个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”/>全选/取消全选 <script type="text/javascript"> <!-- $(function() { $("#checkedAll").click(function() { if ($(this).attr("checked") == true) { // 全选 $("input[@name='checkbox_name[]']").each(function() { $(this).attr("checked", true); }); } else { // 取消全选 $("input[@name='checkbox_name[]']").each(function() { $(this).attr("checked", false); }); } }); }); //--> </script>  

=================================================

jquery radio取值,checkbox取值,select取值,radio选中,checkbox选中,select选中,及其相关

获取一组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();//清空下拉框

相关资源:垃圾分类数据集及代码
转载请注明原文地址: https://www.6miu.com/read-5053815.html

最新回复(0)