简体   繁体   中英

Populate textbox from checkbox list using ASP.NET and AJAX

I have a textbox control and a checkbox list control on my page.

I am first populating my checkbox list with a list of employee objects in the code-behind. An employee has an id and a name. Both are displayed in the checkbox list like so:

  • Jim (1)
  • Alex (2)
  • Gary (3)

When a user checks one of the boxes, the employee's name needs to be populated in the textbox. So if Jim is selected, the textbox value is "Jim". It also needs to support multiple values, so if Jim and Gary are selected, the textbox value is "Jim, Gary".

Also, if a user enters a valid value in the textbox, the correct employee should be checked. This needs to support names and id's. So if I enter "1,Alex" in the textbox and then click outside the textbox, Jim and Alex should be selected.

I'm using ASP.NET and I need to do this using AJAX, but I have no experience with using jQuery and AJAX. Could someone show me a simple example of how to do this?

Here is something I through together that might help get you started. It's not tested and not complete but I don't have time to do it all right now, so thought this might help. There definitely needs to be a lot more checks and paring done that I left out for you to implement.

$(function() {
    // gets all checkbox items by a common class you will put on all of them
    $('.checkboxlistclass').click(function(e) {
        var txt = $(this).text();
        var employeeName = txt; // change this to parse out the name part and remove the id

        var currentTxtVal = $('#textboxid').val();
        var newVal = currentTxtVal + ',' + employeeName; // check if you need the comma or not

        $('#textboxid').val(newVal);
    });

    // textboxid is the id of the textbox
    $('#textboxid').change(function(e) {
        var textboxVal = $(this).val();

        // split on the comma and get an array of items
        // this is dummy data
        var items = [];
        items.push('Jim');
        items.push(2);

        // go through all the items and check if it's a number or not
        // if it's a number do a selection based on the id in parenthesis
        // if not then check first part for name match
        for (var i=0; i < items.length; i++) {
            if (isNaN(parseInt(items[i])) {
                $(".checkboxlistclass:contains('" + items[i] + " ('").attr('checked', true);
            }
            else {
                $(".checkboxlistclass:contains(' (" + items[i] + ")'").attr('checked', true);
            }
        }
    });
});

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