复选框将所有选项而不是一个存储到数据库中

时间:2018-12-04 18:25:38

标签: javascript php

当前,当我仅选择一个选项(例如C)时,我的复选框值将作为[“ A”,“ B”,“ C”]存储到数据库中。另外,我还有另一个问题-是否可以将其存储为ABC?

$(document).ready(function() {
  "use strict";

  var role;
});

function savenewuser() {
  var url = serverURL() + "/newadmin.php";
  checklist = new Array();
  $('input:checkbox[name="roles[]"]').each(function() {
    checklist.push($(this).val());
  });

  role = JSON.stringify(checklist);

  $.ajax({
    url: url,
    type: 'GET',
    data: {
      "role": role,
    },
    success: function(arr) {
      _getNewUserResult(arr);
    },
    error: function() {
      alert("error");
    }
  });
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div><label for="rights">Rights</label></div>
<input type="checkbox" name="roles[]" value="A">Bookings
<input type="checkbox" name="roles[]" value="B">Incident Booking
<input type="checkbox" name="roles[]" value="C">Edit User

1 个答案:

答案 0 :(得分:5)

You're saving all the checkboxes:

$('input:checkbox[name="roles[]"]').each(function() {
    checklist.push($(this).val());
});

Try saving :checked ones only:

$('input:checkbox[name="roles[]"]:checked').each(function() {
    checklist.push($(this).val());
});