Reputation: 107
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 // ????
};
Upvotes: 4
Views: 580
Reputation: 337560
You appear to be asking how to return the data from the function to the property. As such, add a return
statement in the function, and invoke it from the property by adding ()
at the end of the function name, like this:
function getCheckedMaterials() {
var materialArray = $("#materiallist input:checked").map(function () {
return this.value;
}).get();
return materialArray.join(',');
}
$('#tallenna').click(function (e) {
e.preventDefault();
var form = {
// other properties...
MaterialName: getCheckedMaterials()
};
// send 'form' in an AJAX request here...
});
I would suggest returning the plain materialArray
array from the function and sending that in your AJAX request to your WebAPI endpoint. That way you can modelbind it to a string[]
or IEnumerable<string>
which makes it easier to work with.
Upvotes: 1