使用jQuery基于复选框的选中和取消选中更新数组

时间:2017-06-16 18:49:33

标签: jquery

我有以下代码,在检查复选框时将值推送到数组中。

var complaintIds = [];

function select_tickets() {
 $(".take_tickets").css('display', 'block');
 var id = $(this).data("id");
 complaintIds.push(id);
}

$('body').on('click', '.select_ticket', select_tickets);

但是,如果未选中已选中的复选框,则无法从数组中删除值。除此之外,再次添加相同的值。

有人可以告诉我我做错了什么吗?

感谢。

2 个答案:

答案 0 :(得分:0)

试试这个

  $request = new FacebookRequest( $session, 'GET', '/me' );
  $response = $request->execute();
  // get response
  $graphObject = $response->getGraphObject();
        $fbid = $graphObject->getProperty('id');              // To Get Facebook ID
        $fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
        $femail = $graphObject->getProperty('email');    // To Get Facebook email ID
        $flocation = $graphObject->getProperty('location');
    /* ---- Session Variables -----*/
        $_SESSION['FBID'] = $fbid;           
        $_SESSION['FULLNAME'] = $fbfullname;
        $_SESSION['EMAIL'] =  $femail;
        $_SESSION['location'] =  $flocation;
    /* ---- header location after session ----*/

<强>演示

var complaintIds = [];

function select_tickets(el) {
 $(".take_tickets").css('display', 'block');
 var id = $(el).data("id");
 if(el.checked){
   complaintIds.push(id);
 }else{
   complaintIds = $.grep(complaintIds, function(value) { return value !== id; });   // remove id from array if unchecked
 }
 console.log(complaintIds);
}

$('body').on('change', '.select_ticket', function(){select_tickets(this)});
var complaintIds = [];
function select_tickets(el) {
 $(".take_tickets").css('display', 'block');
 var id = $(el).data("id");
 if(el.checked){
   complaintIds.push(id);
 }else{
   complaintIds = $.grep(complaintIds, function(value) { return value !== id; });   // remove id from array if unchecked
 }
 console.log(complaintIds);
}

$('body').on('change', '.select_ticket', function(){select_tickets(this)});

答案 1 :(得分:0)

这应该做的工作:

"replace": { "symfony-cmf/routing-auto":"2.0.0-RC1" },

小提琴测试它 https://jsfiddle.net/2L38x4u9/