【问题标题】:getting the value of multiple checkboxes and using ajax to preform an action with their values获取多个复选框的值并使用 ajax 对其值执行操作
【发布时间】:2012-10-24 23:44:44
【问题描述】:

我有一个带有复选框的表,如果选中了一个复选框,我希望删除数据库中的原始数据 - 使用 ajax。

使用普通形式,我会简单地命名所有复选框,一些名称可以说 name="checkbox[]" 然后只需使用 foreach($_POST['checkbox'] as $value){}

现在我正在尝试获取标记复选框的所有值,然后将它们放入数组中。似乎我错过了一些东西。这是我到目前为止所做的:

var checkboxes = jQuery('input[type="checkbox"]').val();
var temp = new Array();
jQuery.each(checkboxes, function(key, value) { 
     temp[] = value;
});

稍后我只会将 temp 作为变量传递给 ajax 调用。

我有什么遗漏吗?

【问题讨论】:

  • 请注意,JavaScript 不是 Java。

标签: javascript jquery html


【解决方案1】:

你可以使用:checked选择器和map方法:

var arr = $('input[type="checkbox"]:checked').map(function(){
     return this.value
}).get();

【讨论】:

  • 链式 .get() 的目的是什么? .map 将返回一个数组。
  • @MattStone map 返回一个 jquery 包装的数组,get 返回实际的数组。
  • 你确定吗?文档 (api.jquery.com/jQuery.map) 或快速测试 (jsfiddle.net/2aSdZ) 并未表明情况如此。
  • @MattStone 是的,你使用的是 $.map 实用函数,我已经使用了这张地图api.jquery.com/map
  • @MattStone 看到这个jsfiddle.net/k96VX 没有得到你将有 TypeError: arr.join is not a function
【解决方案2】:

您正在尝试迭代错误的 Checkbox 值。试试这个

var $checkboxes = jQuery('input[type="checkbox"]') ;
var temp = new Array();
jQuery.each($checkboxes, function(i) {
     var value = $(this).attr('value'); 
     temp[i] = value;
});

如果您只想通过检查项,只需添加一个条件。

if($(this).is(':checked')){
  var value = $(this).attr('value'); 
  temp[i] = value;
}

【讨论】:

  • 查看 jQuery.map(),它比 jQuery.each() 更适合此任务。
【解决方案3】:

只需将表格包装在表单标签中,然后执行以下操作:

var myData = jQuery('#myform').serialize();
jQuery.ajax('myscript.php', {data:myData});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-05
    • 2011-03-11
    • 2013-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-23
    相关资源
    最近更新 更多