如何在 jQuery 中检索复选框值 [英] How to retrieve checkboxes values in jQuery

查看:30
本文介绍了如何在 jQuery 中检索复选框值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用 jQuery 获取选中的复选框值,并立即将其放入 textarea?

就像这段代码:

<头><身体><div id="c_b"><input type="checkbox" value="one_name" 选中><input type="checkbox" value="one_name1"><input type="checkbox" value="one_name2">

<textarea id="t"></textarea>

如果 id="c_d"Ajax 更新,下面的 altCognito 代码不起作用.有什么好的解决办法吗?

解决方案

这是一个有效的方案(查看示例):

 函数 updateTextArea() {var allVals = [];$('#c_b :checked').each(function() {allVals.push($(this).val());});$('#t').val(allVals);}$(函数(){$('#c_b input').click(updateTextArea);更新文本区域();});

更新

几个月后,另一个问题是关于如何在 ID 更改时保持上述工作.好吧,解决方案归结为将 updateTextArea 函数映射到使用 CSS 类的通用函数,并使用 live 函数来监视 DOM 的这些更改.

How to use jQuery to get the checked checkboxes values, and put it into a textarea immediately?

Just like this code:

<html>
  <head>
  </head>

  <body>
    <div id="c_b">
      <input type="checkbox" value="one_name" checked>
      <input type="checkbox" value="one_name1">
      <input type="checkbox" value="one_name2">
    </div>  

    <textarea id="t"></textarea>
  </body>
</html>

If the id="c_d" is updated by Ajax, the below of altCognito's code doesn't work. Is there any good solution?

解决方案

Here's one that works (see the example):

 function updateTextArea() {         
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });
     $('#t').val(allVals);
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

Update

Some number of months later another question was asked in regards to how to keep the above working if the ID changes. Well, the solution boils down to mapping the updateTextArea function into something generic that uses CSS classes, and to use the live function to monitor the DOM for those changes.

这篇关于如何在 jQuery 中检索复选框值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆