【问题标题】:how to insert checkbox value without using array in jquery如何在jquery中不使用数组插入复选框值
【发布时间】:2017-04-24 17:33:41
【问题描述】:

我想将复选框值插入数据库,当我单击特定复选框时,必须插入相应的值,但对我来说,之前选中的复选框值也再次插入到数据库中,我该如何克服这个问题?
如果我选中了复选框 1,再次插入到数据库中,我选中了复选框 2,我的表格显示了 checkbox1、checkbox1、checkbox2。
在这里我使用了 foreach 循环它的问题或任何其他方法来解决这个问题。

JS 代码:

$("input[type=checkbox]").on("change", function() {
  var ids = [];
  var dis = [];
  $('input[type=checkbox]:checked').each(function() {
    ids.push($(this).val());
  });
  $('input[type=checkbox]:not(:checked)').each(function() {
    dis.push($(this).val());
  });
  dis = dis.toString();
  ids = ids.toString();
  $.ajax({
    url: "bodcheckbox.php",
    type: "POST",
    async: true,
    cache: false,
    data: ({
      value: ids,
      unchecked: dis,
    }),
    dataType: "text",
    success: function(data) {
      alert("activitysubmitted");
    }
  });
});

PHP 代码:

session_start();
include 'config.php';
$username = $_SESSION['username'];
//if(isset($_POST['value']))
//{
//unchecked box value--
$unchecked       = $_POST['unchecked'];
$uncheckboxvalue = array();
$uncheckboxvalue = explode(",", $unchecked);
//--checkedbox value--
$checkbox    = array();
$checklist   = $_POST['value'];
$checkbox    = explode(",", $checklist);
$currentdate = date('d-m-Y');
$year        = date('Y', strtotime($currentdate));
$month       = date('F', strtotime($currentdate));
$date        = date('d', strtotime($currentdate));
date_default_timezone_set('Asia/Kolkata');
$currenttime = date("h-i-sa");
if (!empty($checklist)) {
    foreach ($checkbox as $check) {
        $bod_insert = mysql_query("insert into bod(username,activityname,tickeddate,tickedtime,status)values('$username','" . mysql_real_escape_string($check) . "','$date-$month-$year','$currenttime','yes')", $conn);
    }
    foreach ($uncheckboxvalue as $uncheck) {
        $bod_update = mysql_query("update bod set status='no' where activityname='" . mysql_real_escape_string($uncheck) . "' and username='$username'", $conn);
    }
}

【问题讨论】:

  • 你想只插入当前选中元素的值吗?
  • yes madalin only current checkbox value

标签: jquery


【解决方案1】:

您可以尝试这样的方法来获取当前选中元素的当前状态:

$("input[type=checkbox]").on("change", function() {
var ids = null;//set to null for unchecked
if (this.checked) {//set the value for checked
  var ids =$(this).val();
}
  $.ajax({
    url: "bodcheckbox.php",
    type: "POST",
    async: true,
    cache: false,
    data: ({
      value: ids,
    }),
    dataType: "text",
    success: function(data) {
      alert("activitysubmitted");
    }
  });
});

【讨论】:

  • 感谢 madalin 如果再次取消选中复选框意味着我必须将状态更新为='no'
  • 是的,在服务器端,您执行 if 来测试该值是 null 还是数字,并基于此更新您的状态
【解决方案2】:

您需要通过查询表是否有具有相同活动和相同用户名的记录来检查。获取结果计数,如果为0则插入记录,否则无变化

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-23
    • 2011-10-19
    • 2017-01-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多