Set Default Value in HTML CheckBox on Page Load using jQuery

Last Reply 2 months ago By dharmendr

Posted 2 months ago

How to set default value as " true "when page load

in order to set as value "true" and "false" for post to database

        [HttpPost]
        public ActionResult AddDepartement(Departement dept)
        {
            dept = new Departement()
            {
                departement = dept.departement,
                active = dept.active,
                create_date = DateTime.Now
            };
            db.Departements.Add(dept);
            db.SaveChanges();

            return RedirectToAction("Index");
        }

 

            <div class="col-sm-6">
                <div class="input-group">
                    <span class="input-group-addon" style="width:41px"><i class="fa fa-id-card"></i></span>
                    <input type="checkbox" class= "form-control" onload="true" data-toggle="toggle" id="Active" data-on="True" data-off="False" checked="checked">
                </div>
            </div>

 

    // change value toggle active when click
    $(document).ready(function () {

        $("input[id=Active]").change(function () {
            if ($(this).prop("checked")) {
                $(this).val("True");
            } else {
                $(this).val("False");
            }
        });
    });

 

Posted 2 months ago

Hi Ruben12345,

Refer below code.

HTML

<div class="col-sm-6">
    <div class="input-group">
        <span class="input-group-addon" style="width: 41px"><i class="fa fa-id-card"></i>
        </span>
        <input type="checkbox" class="form-control" onload="true" data-toggle="toggle" id="Active"
            data-on="True" data-off="False" checked="checked" />
    </div>
</div>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("input[id=Active]").attr('value', 'True');
        $("input[id=Active]").change(function () {
            if ($(this).prop("checked")) {
                $(this).attr('value', 'True');
            } else {
                $(this).attr('value', 'False');
            }
        });
    });
</script>

Demo