PDA

View Full Version : How to Save multiple checkbox values to sql database?



johnwest
08-27-2019, 04:32 PM
I have a html form, and i have also checkboxes in it. Values of checkboxes is coming from SQL-database via Web Api.

$(document).ready(function () {
var $MaterialName = $('#materiallist');

function addMaterials(material) {
$MaterialName.append('<input type="checkbox" >' + material.MaterialName + ' </input>');
}
<div class="form-group">
<label for="material" class="col-xs-3 control-label header">Käytetyt materiaalit</label>
<div class="col-xs-7">
<div class="checkbox" id="materiallist"></div>
</div>
</div>
I want to save those checked values to another SQL-database (named Form), along with the other input values in that form.

I haven't found a solution where all the other input fields also needs to be saved as well, only solutions where is only checkboxes and button. Also, my values are coming from a database, and are not "hard-coded" options.

I tried this:

function getCheckedMaterials() {
var materialArray = [];
$("#materiallist input:checked").each(function () {
materialArray.push($(this).val());
});
var selected;
selected = materialArray.join(',');
alert("You have selected " + selected);
}
This doesn't work as I need, because I can't get the values.

All these values from other input fields goes to the Form database when I press the #tallenna button. I need the checked values to be saved in MaterialName as text.

$('#tallenna').click(function () {
var form = {
FormFiller: $FormFiller.val(),
CustomerContact: $CustomerContact.val(),
ReadyToDate: $ReadyToDate.val(),
Instructions: $Instructions.val(),
Amount: $Amount.val(),
PcsAmount: $PcsAmount.val(),
ChargeFull: $ChargeFull.val(),
ChargeByPcs: $ChargeByPcs.val(),
FreightCost: $FreightCost.val(),
CustomerName: $CustomerName.val(),
WorkName: $WorkName.val(),
MaterialName: getCheckedMaterials // ????
};

tomsfashion2019
08-28-2019, 06:33 AM
For checkboxes, only those you select will be sent to the server. And if you name them all like boxes[] the selected boxes will be sent as an array.

Consider this example:
01
<!DOCTYPE html>
02
<html>
03
<head><title>Example</title></head>
04
<body>
05
<form action="" method="post">
06
<input type="checkbox" name="boxes[]" value="1">1</input>
07
<input type="checkbox" name="boxes[]" value="2">2</input>
08
<input type="checkbox" name="boxes[]" value="3">3</input>
09
<br><input type="submit">
10
</form>
11
<pre><?php
12
if(isset($_POST['boxes']))
13
{
14
foreach ($_POST['boxes'] as $_boxValue)
15
{
16
echo "Box #{$_boxValue} was selected!\n";
17
}
18
}
19
?></pre>
20
</body>
21
</html>

BangkokDinning
08-28-2019, 10:01 AM
Each checkbox is a simple True/False value. Unless you're using a TriState checkbox that is...

If you're using a normal checkbox, you check either use one database field for each checkbox, or you can assign bit flag values to each checkbox and "OR" those togther and save the resulting value.