skip to Main Content

I am looking to append some checkboxes using a result of data from an Ajax call, However I am having a bit of trouble doing this.. My Response[i] items when iterating seem to be undefined. Additionally, whats outputted is being rendered in the list as raw html. I am unsure if this is a syntax issue or I am simply not handling the js correctly.

Here is my json data result and its format when passed to the success function of my AJAX call:

{"data":[{"Id":42,"text":"IMPR"},
         {"Id":62,"text":"AMFG"},
         {"Id":63,"text":"AIMP"},
         {"Id":64,"text":"OTHR"},
         {"Id":73,"text":"BSA"}
        ]
}

I am using the Bootstrap multiselect as a userControl so it can be used on any page we like as it is a very nice nuance to the standard dropdown list. Here is the usercontrol .ascx page.

$(function() {
  $('[id*=ddlListBox]').multiselect({
    includeSelectAllOption: false,
    templates: {
      button: '<button type="button" class="multiselect dropdown-toggle" data-bs-toggle="dropdown"><span class="multiselect-selected-text"></span></button>'
    }
  });
});
.btn-group {
  width: fit-content;
  border: 1px solid #000000;
}

.btn-group ul {
  width: 500px !important;
}

.btn-group ul li:hover {
  /*border:1px solid red;*/
  background-color: #3D59AB;
  color: white;
}
<div class="form-group col-sm-5">
  <asp:ListBox ID="ddlListBox" class="ddlchkBox form-control form-select" runat="server" SelectionMode="Multiple">
  </asp:ListBox>
</div>

What I am trying to accomplish is to add the additional checkboxes to the ul as li elements. Populating the value of the checkbox with the ‘value’ fields from json data and the Ids as the ‘Id’ fields of the json data.

Ajax success function:

$jq.ajax({
  contentType: 'application/json; charset=utf-8',
  dataType: 'json',
  type: 'POST',
  url: 'Messages.aspx/GetSeriesforFormIds',
  data: "{'data':'" + JSON.stringify(formIds) + "'}",
  success: function(data) {
    debugger;
    if (data.d != null) {
      var container = document.querySelector('.ddlchkSeriesCheckboxes');
      var checkboxes = container.querySelector('.multiselect-container');
      var temp = data.d;
      if (temp != '') {
        var Response = temp.split(",");
        if ((temp != '') && (temp.length > 0)) {
          for (i = 0; i < Response.length; i++) {
            checkboxes.append('<li><a tabindex="0"><label class="checkbox"><input type="checkbox" value="' + Response[i].Id + '">' + Response[i].Text + '</label ></a ></li >')
            //$("#ddlchkSeries").append("<input type='checkbox' id='chk-" + i + "' name='" + Response[i] + "' /> " + Response[i]);

          }
        }
      }
    }
  },
  error: function(response) {
    //alert(JSON.stringify(response));
  }
});

Here is the structure of my rendered html: (I know code is preferred here, but there is too much embedded JS to use code snippets):

enter image description here

I need to add my json data results as listItem checkbox elements in the highlighted area. I thought I was coming close with the .append method, but what is rendered is literal html, rather than rendered controls.

Any help would be greatly appreciated.

2

Answers


  1. Chosen as BEST ANSWER

    UPDATE: Thank you all for your help in figuring this out. After parsing the json, I was able to successfully see the results I wanted with this update to my success function without the need to use createElement() to make the custom control as I found that to be extremely cumbersome.

      $jq.ajax({
                            contentType: 'application/json; charset=utf-8',
                            dataType: 'json',
                            type: 'POST',
                            url: 'Messages.aspx/GetSeriesforFormIds',
                            data: "{'data':'" + JSON.stringify(formIds) + "'}",
                            success: function (data) {
                                //debugger;
                                if (data.d != null) {
                                    
                                    var $checkboxContainer = $('.ddlchkSeriesCheckboxes .multiselect-container');
    
                                    var temp = data.d;
    
                                    if (temp != '') {
                                  
                                        debugger;
                                            var obj = $.parseJSON(temp);
    
                                        if ((obj != '') && (obj.data.length > 0)) {
                                            for (i = 0; i < obj.data.length; i++) {
                                                $checkboxContainer.append('<li><a tabindex="0"><label class="checkbox"><input type="checkbox" value="'+obj.data[i].Id+'">'+obj.data[i].text+'</label ></a ></li >')
                                            }
                                        }
    
                                    }
                                }
                            },
                            error: function (response) {
                                //alert(JSON.stringify(response));
                            }
                        });
    

  2. You need to parse the data properly and use jQuery to append

    $('.multiselect-container').append(
      response.data
      .map(entry => `<li><a tabindex="0"><label class="checkbox"><input type="checkbox" value="$entry.Id">${entry.text}</label ></a ></li >`)
      .join('')
    )
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <ul class="multiselect-container"></ul>
    
    <script>
      const response = {
        "data": [{
            "Id": 42,
            "text": "IMPR"
          },
          {
            "Id": 62,
            "text": "AMFG"
          },
          {
            "Id": 63,
            "text": "AIMP"
          },
          {
            "Id": 64,
            "text": "OTHR"
          },
          {
            "Id": 73,
            "text": "BSA"
          }
        ]
      }
    </script>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search