Reputation: 111
First of all, thank you for your help. I'm pretty new.
This should be super simple but I've spent hours trying to figure this out. I have a form in my view. The form is populating everything correctly - except for the checkbox. I've researched and researched and tried a lot of different suggestions online. No matter what I try, the form sets the same value for checked and unchecked.
View:
<div class="checkbox">
<label>
<input id="lunch45" type="checkbox" value="true">45 minute lunch
</label>
</div>
jQuery:
<script>
$(document).ready(function () {
$("#Lunchsubmit-form").click(function () {
var model = {};
model.EmployeeID = Number($("#lunchemployeeId").val());
model.LunchTime = Date($('#lunchtimeId').val());
model.PositionID = Number($("#lunchposition").val());
model.LongerLunch = Boolean($('#lunch45').val());
console.log("model", model);
$.ajax({
type: "HttpPost",
url: "/Home/CreateLunch",
dataType: 'json',
data: JSON.stringify(model),
contentType: "application/json; charset=utf-8",
success: function (data) {
if (data.success)
window.location.href = "/Home/Index";
else
alert("Error: Lunch not submitted");
},
error: function () {
alert("Error: Lunch not submitted");
}
});
});
});
</script>
Model:
public class Lunch
{
public int LunchID { get; set; }
public int EmployeeID { get; set; }
public DateTime LunchTime { get; set; }
public int? PositionID { get; set; }
public bool LongerLunch { get; set; }
public virtual Employee Employee { get; set; }
public virtual Position Position { get; set; }
}
Thanks again. I know how simple this should be but nothing's working.
Upvotes: 1
Views: 570
Reputation: 5274
Try using 1 and 0 , read about JS Boolean function here
Check
alert(Boolean(Number("0")));
alert(Boolean(Number("1")));
Then
<input id="lunch45" type="checkbox" value="0" />
...
model.LongerLunch = Boolean(Number($('#lunch45').val()));
Or use checkbox directly
model.LongerLunch = $('#lunch45').is(":checked");
Or maybe you need verify is checked, before get the value
<input id="lunch45" type="checkbox" value="0" >
<input id="lunchx" type="checkbox" value="1" checked>
alert($('#lunch45').is(":checked"));
alert($('#lunchx').is(":checked"));
Upvotes: 1