使用ASP.NET和AJAX从复选框列表填充文本框

时间:2010-08-02 21:18:32

标签: c# asp.net jquery ajax

我的页面上有一个文本框控件和一个复选框列表控件。

我首先使用代码隐藏中的员工对象列表填充我的复选框列表。员工有一个id和一个名字。两者都显示在复选框列表中,如下所示:

  • 吉姆(1)
  • Alex(2)
  • Gary(3)

当用户选中其中一个框时,需要在文本框中填充员工的姓名。因此,如果选择Jim,则文本框值为“Jim”。它还需要支持多个值,因此如果选择Jim和Gary,则文本框值为“Jim,Gary”。

此外,如果用户在文本框中输入有效值,则应检查正确的员工。这需要支持名称和ID。因此,如果我在文本框中输入“1,Alex”,然后在文本框外单击,则应选择Jim和Alex。

我正在使用ASP.NET,我需要使用AJAX这样做,但我没有使用jQuery和AJAX的经验。有人能告诉我一个如何做到这一点的简单例子吗?

1 个答案:

答案 0 :(得分:2)

这是我在一起的东西,可能有助于你开始。它没有经过测试而且没有完整,但我现在没有时间去做,所以认为这可能会有所帮助。肯定需要做更多的检查和削减,我留给你实施。

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