0

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.

3
  • 1
    MDN indicates that you can pass objects or strings to append(); you are passing a string. If you want to append an element, you'll need to build the element using methods such as document.createElement(). Or set the innerHTML with the string you're currently using. Commented Oct 22, 2024 at 15:42
  • UPDATE: Thank you for this! I am able to get the empty control added to the page using your information about the createElement method. I , however, I am still having trouble getting the text and values from my json data used for the value and text fields for the checkboxes. Right now, for testing purposes I am statically assigning text and value. Commented Oct 22, 2024 at 16:08
  • 1
    var $checkboxContainer = $('.ddlchkSeriesCheckboxes .multiselect-container'); Now you can use append to $checkboxContainer Commented Oct 22, 2024 at 16:09

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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));
                        }
                    });

1 Comment

So data.d is a JSON string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.