3
Answers

when checkbox is unchecked it passes null value instead of 0

kaushik guru

kaushik guru

2y
1.3k
1

i am using a check box to validate the input given by user.  the view is as follows

<script>
    // this is the scrpt for checkbox
    $(document).on("click", "[type='checkbox']", function (e) {
        if (this.checked) {
            $(this).attr("value", "1");
        } else {
            $(this).attr("value", "0");
        }
    });
</script>

<div class="row mb-2">
    @if(Model.Is_Prefix_Checked == 1)
    {
        <div>
        <div class="col-md-1" style='align-content:center;'>
            <input type="checkbox"  class="largerCheckbox" id="Is_Prefix_Checked" name="IsPrefixChecked" value="1" checked="checked" >
        </div>
    </div>
    }
    else
    {
        <div>
        <div class="col-md-1" style='align-content:center;'>
                <input type="checkbox" class="largerCheckbox" id="Is_Prefix_Checked" value="0" name="IsPrefixChecked">
        </div>
    </div>
    }
    <label class="col-sm-2 col-form-label">Prefix</label>
    <div class="col-sm-3">
        <select asp-for="EmployeePrefix" class="form-control" asp-items="@ViewBag.prefix"  >
        </select>
        <span asp-validation-for="EmployeePrefix" class="text-danger" ></span>
    </div>
</div>
JavaScript

When the check box is unchecked it passes null instead of 0 

in my model i as follows

public int? isprefixchecked {get; set;}
C#

Kindly help

Answers (3)
5
Sachin Singh

Sachin Singh

11 55.8k 87.1k 2y

Test this

$('input[type="checkbox"]').change(function(){
    this.value = (Number(this.checked));
});
5
Naimish Makwana

Naimish Makwana

137 13.8k 199.7k 2y

Hello Kaushik,

Your model property isprefixchecked is of type int?. which is expecting either an integer value or null. So you need to cast the value to an integer before setting it to the model property

$(document).on("click", "[type='checkbox']", function (e) {
    var value = this.checked ? 1 : 0;
    $(this).attr("value", value);
});

Thanks

Naimish Makwana

4
Rijwan Ansari

Rijwan Ansari

4 66.3k 3m 2y

Hi 

Select your checkbox with Id reference.

Example:

const checkbox = document.getElementById('Is_Prefix_Checked')
checkbox.addEventListener('change', (event) => {
  var value = this.checked ? 1 : 0;
    $(this).attr("value", value);
})