Joseph Nields
Joseph Nields

Reputation: 5661

How to identify ASP control between jQuery and code behind?

I have this to make an auto complete happen:

jQuery(function($) {
    $("input[type='text']").autocomplete();
    $("input[type='text']").keyup(function(event) {
        var $this = $(this);
        var id = $this.attr('name');
        var params = {'id': id, 'partial': $this.val()};
        var jsonParams = JSON.stringify(params);
        $.ajax({
            type: "POST",
            url: "MyPage.aspx/GetAutoCompleteList",
            data: jsonParams,
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function(msg) {
                $this.autocomplete('option','source', JSON.parse(msg.d));
            }
        });
    });
});

and a way to call it:

[WebMethod]
public static String GetAutoCompleteList(string id, string partial)
{
    AutoCompleter completer;
    switch (id)
    {
        case "first-name":
            completer = first_names;
            break;
        case "last-name":
            completer = last_name;
            break;
        case "site":
            completer = site_numbers;
            break;
        case "institution":
            completer = institutions;
            break;
        // ....
        default:
            return "[]";
    }
    return jsSerializer.Serialize(toUse.CloseMatches(partial));
}

AutoCompleter just finds some potential matches and returns them as an array.

I'm running into a problem, because I'm not sure how to actually identify the inputs. Here's an example of one:

<asp:TextBox runat="server" name="first-name" id="first-name" AutoPostBack="true"></asp:TextBox>

BUT $this.attr('name') won't return first-name. It's instead some auto-generated ASP.NET nonsense. What's an easy way to definitively identify this input?

I mean, we could just do:

<div class="hacky" name="first-name" style="display:none"></div>
<asp:TextBox ... ></asp:TextBox>

and

var id = $this.siblings(".hacky").attr('name');

but there has to be an easier way.

Upvotes: 1

Views: 52

Answers (1)

Ziv Weissman
Ziv Weissman

Reputation: 4516

  1. You can use static ID for your text input by adding:

ClientIDMode = "Static"

  1. If you have many, you can use static ID for all in the web.config

  2. You can use some custom attribute like attr-data-id=(AspControll).ClientID

Upvotes: 2

Related Questions