简体   繁体   中英

Validate at least one auto generate jquery datatable checkbox is checked using MVC

Trying to make sure the user select at least one check box before submitting the form. At the moment my JavaScript is not working. The checkbox is auto generate in the jquery datatable. The code is still getting to the controller even when none of the checkbox in the table is not selected

HTML

 <table id="scheduleAppointment-data-table" class="table table-striped table- bordered" style="width:100%;"></table>    
  <input type="submit" value="Send" class="btn btn-default" id=btnSubmit onclick="Validate()"/>

Datatable

      // Auto generate checkbox
      "columns": [
             {
               targets": [0],
                "data": "EDMXID", "autoWidth": true,              
                 "render": function (data, type, full) {
                 return '<input type="checkbox" id="EDMXID" name="EDMXID" value="'+full.EDMXID+'"/>';
              },
               }]

Javascript

 function Validate() {
        var allOk = true;
     $(scheduleAppointment-data-table).find("tbody tr").each(function (){
            var row = $(this);
            var checked = row.find($(':checkbox:checked')).length > 0
            if (!checked) {
                allOk = false;
                alert('At least One Appointment Should Be Selected');
                return allOk;
            }
        });
        return allOk;
    }

With help from Davidkonrad comment I finally used the JavaScript code below

 $(function () {
        $('input[id$=btnSubmit]').click(function (e) {
            $('#scheduleAppointment-data-table').find("tbody tr").each(function () {
                var row = $(this);
                var checked = row.find($(':checkbox:checked')).length > 0
                if (!checked) {
                    alert('At least One Appointment Should Be Selected');
                    e.preventDefault();
                }
            });
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM