Dynamically Create Checkboxes from AJAX Response

后端 未结 2 1909
后悔当初
后悔当初 2021-01-22 09:57

I\'m creating a website involving bootstrap and want to display a list of checkboxes (names of computers) in a modal dialog for the user to choose from. I have an AJAX call and

相关标签:
2条回答
  • 2021-01-22 10:19

    This can be best achieved by using ngRepeat from AngularJS: https://docs.angularjs.org/api/ng/directive/ngRepeat

    If you include it in your project, I hope it will lower 20-30% of the code logic that you you are searching for or having issues like this.

    For further details here is the link: https://angularjs.org/

    At last you have other choices too, but I just wanted to share the smartest framework in JS with you.

    Happy coding!
    :)

    0 讨论(0)
  • 2021-01-22 10:33

    Below is an example of what you could use in your success function to accomplish this.

    The changes to what you had include wrapping each checkbox in a <li> and adding a corresponding <label> for it.

    // sample of response from server
    var response = { optionA: 'One', optionB: 'Two', optionC: 'Three' };
    
    // this would go in your ajax success handler
    $.each(response, function (key, value) {
        var li = $('<li><input type="checkbox" name="' + key + '" id="' + key + '"/>' +
                   '<label for="' + key + '"></label></li>');
        li.find('label').text(value);
        $('#wkslist').append(li);
    });
    #wkslist {
        list-style-type: none;
        padding: 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <ul id="wkslist"></ul>

    0 讨论(0)
提交回复
热议问题