javascript - 获取所有选中复选框的列表

标签 javascript jquery checkbox

我想弄清楚哪些复选框被选中,所以我尝试了这段代码:

$('.feature input[type="checkbox"').serialize();

这是我的 HTML 的样子:

<div class="feature">
  <h2>Features</h2>
  <label><input class="custom_css" checked="" type="checkbox" name="feature[]"> Custom CSS (style.css)</label>
  <label><input class="custom_js" checked="" type="checkbox" name="feature[]"> Custom Javascript (script.js)</label>
  <label><input class="modernizr" type="checkbox" name="feature[]"> Modernizr</label>
  <label><input class="google_maps" type="checkbox" name="feature[]"> Google Maps</label>
  <label><input class="custom_api" type="checkbox" name="feature[]"> Custom API</label>
  <label><input class="font_awesome" type="checkbox" name="feature[]"> Font Awesome</label>
</div>

这是我得到的输出:

array(1) { ["var_sent_via_ajax"]=> string(67) "feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on" }

现在我怎么知道哪些已经被选中了?符号 %5B%5D 是什么意思?

最佳答案

关于:%5B %5D
回答:它们只是 [ ] 的原始 HTTP 编码值(序列化函数的结果)。
当服务器解析它时,它会将其转换为 [] 并将其发送给将被视为数组的应用程序。

关于你为什么会变成假人:feature%5B%5D=on&feature%5B%5D=on... string
答:您忘记给每个复选框一个值参数,那么它们将像:feature%5B%5D=custom_css&feature%5B%5D=custom_js...

我写了解决方案。
以这个工作示例为例,像字符串一样处理服务器端应用程序请求的“功能”参数,并通过 , 缩小它(php: $features = explode(',', $_POST[ '功能']);

$(function() {
  
  $('#getFeatures').click(function() {
    var features = [];
    $('.feature input[type="checkbox"]:checked').each(function() {
      features.push($(this).val());
    });
    $('#selectedFeatures').html(features.join(','));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="feature">
  <h2>Features</h2>
  <label><input class="custom_css" checked="" type="checkbox" name="feature[]" value="custom_css"> Custom CSS (style.css)</label>
  <label><input class="custom_js" checked="" type="checkbox" name="feature[]" value="custom_js"> Custom Javascript (script.js)</label>
  <label><input class="modernizr" type="checkbox" name="feature[]" value="modernizr"> Modernizr</label>
  <label><input class="google_maps" type="checkbox" name="feature[]" value="google_maps"> Google Maps</label>
  <label><input class="custom_api" type="checkbox" name="feature[]" value="custom_api"> Custom API</label>
  <label><input class="font_awesome" type="checkbox" name="feature[]" value="font_awesome"> Font Awesome</label>
</div>

<button id="getFeatures">GET FEATURES</button>
<div id="selectedFeatures"></div>

关于javascript - 获取所有选中复选框的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38185847/

相关文章:

javascript - Webpack - 忽略 require() 中的加载器?

javascript - 使用 JNA、Rhino、JavaScript 分配字符缓冲区

jquery - TableTools 仅导出单个标题行

javascript - 使用 jQuery 检查下一个悬停项目

android - 如何更改 CheckBox 正方形的颜色?

JavaFX 2 - Tableview 复选框不显示值

javascript - 如何使用 Redux 访问本地 JSON 文件以在整个 React 应用程序中使用?

javascript - 如何使用 JQuery 中的 anchor 标记从其他页面选择特定选项卡?

PHP:删除选中的行

javascript - 如果 div 没有内容隐藏其他 div