如何在复选框单击时映射下拉列表和数组中的动态复选框值

时间:2018-03-28 11:02:00

标签: javascript jquery

我一直在尝试获取数组中的下拉值和复选框,并传递给控制器​​

功能: 选中该复选框后。获取数组中所选下拉值和复选框值的值

function getData() {
  if ($("#Cohort_ID").val() == "" || $("#Cohort_ID").val() == "Select") {
    alert("Please Select Cohort");
  } else {
    var checkedCheckBoxesValueArray = $('input:checkbox:checked').map(function() {
      return {
        cohortid: $("#Cohort_ID").val(),
        studentid: this.value
      };
    }).get();
    alert(checkedCheckBoxesValueArray);
  }
}

当下拉列表更改先前所选项目的同类群组ID(下拉列表)也会更改时,此功能仅适用于获取复选框值。

Html代码

  1. For Dropdown

                        

                        @Html.DropDownList("Cohort_ID", null, "Select", htmlAttributes: new { @class = "form-control" })
                        @Html.ValidationMessageFor(model => model.Program_ID, "", new { @class = "text-danger" })
                    </div>
                </div>
    
  2. 复选框

    $(document).ready(function(){     $(“#Program_ID”)。change(function(){

        $.ajax({
            async: true,
            cache: false,
            contentType: "application/json; charset=utf=8",
            type: 'GET',
            url: '/Students/getStudentsByFellowship',
            dataType: 'json',
            data: { programid: $("#Program_ID").val() },
            success: function (students) {
                var table = '<table id="tblStudents" class="table table-bordered table-hover table-responsive table-striped"><thead><tr>';
                table += '<th>Sr. No</th><th>Appliaction No</th><th>Student Name</th><th>Mobile</th><th>Select</th></tr></thead><tbody>';
                $.each(students, function (i, stud) {
                    var checkbox;
                    checkbox = '<input type="checkbox" name="stdentcheckbox" value=' + stud.Student_ID + ' onclick="getData()">';
                        table += '<tr><td>' + parseInt(i + 1) + '</td><td>' + stud.ApplicationNo + '</td><td>' + stud.Name + '</td><td>' + stud.Mobile + '</td>';
                        table += '<td>' + checkbox + '</td></tr>';
                });
                table += '</tbody></table>';
                $("#studenttable").html(table);
                $("#studentdata").css("display", "block");
            },
            error: function (ex) {
                alert('Failed to retrieve states.' + ex);
            },
            failure: function (response) {
                alert('Error while fetching streams');
            }
        });
        return false;
    })
    
  3. 选中复选框时,下拉值为cohortid,复选框选中值作为学生ID并传递给数组。取消选中复选框时删除。

1 个答案:

答案 0 :(得分:-2)

序列化表单数据,它将为您提供所有值