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

Rez*_*eza 3 javascript checkbox jquery

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

$('.feature input[type="checkbox"').serialize();
Run Code Online (Sandbox Code Playgroud)

这是我的 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>
Run Code Online (Sandbox Code Playgroud)

这是我得到的输出:

数组(1) { ["var_sent_via_ajax"]=> 字符串(67) "feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on&feature%5B%5D=on" }

现在我怎样才能知道其中哪些已经被检查过呢?%5B%5D符号是什么意思?

num*_*8er 5

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

关于为什么你得到 dummy: feature%5B%5D=on&feature%5B%5D=on...string
答案:你忘记给每个复选框一个值参数,那么它们将是这样的:feature%5B%5D=custom_css&feature%5B%5D=custom_js...

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

$(function() {
  
  $('#getFeatures').click(function() {
    var features = [];
    $('.feature input[type="checkbox"]:checked').each(function() {
      features.push($(this).val());
    });
    $('#selectedFeatures').html(features.join(','));
  });
});
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)