0

Today I got an interview question as titled.

For example, a Update Panel contains a Panel, the Panel contains a TextBox.

How can I get the TextBox ClientID?

The only I could think of that is:

  1. We can predict the TextBox ClientID depends on the ClientID mode and use getElementByID.

    i.e. getElementByID('ct100$MasterPageBody$ct100$UpdatePanelID$ct100$PanelID$ct100$TextBoxID')

  2. We can use JavaScript to parse the HTML, parse the input controls into arrays.

    i.e Assume we know we want to find the first UpdatePanel's first Panel's first TextBox. We can find it from myUpdatePanel[0] then get its children using JavaScript? (I am only guessing here)

  3. getElementByID('<%=MyTextBox.ClientID%>')

But assuming the TextBox is added dynamic, but what's the proper way of doing it?

1

3 Answers 3

2

You can access the control from a jQuery selector based on the end of the id like the example here:

<asp:CheckBox ID="chkEnable" Text="My Checkbox" runat="server" />
<script type="text/javascript">
    $(function() {
        var checked = $("input[id$=chkEnable]").attr("checked");

    });
</script>

Here's an article for the exact thing: http://weblogs.asp.net/joelvarty/archive/2009/02/09/jquery-get-a-handle-on-a-server-element-in-javascript-without-using-lt-elem-clientid-gt.aspx

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

1 Comment

Excellent answer! Used this to find the id of an asp.net text box on a child control. The traditional "<%=textBox.ClientID%>" won't work since the ClientID call is on a control where the textbox doesn't exist (i.e. the child control). This worked perfectly to get around that problem.
0

Try this JQUERY

$("input[type='text']:first")

Example of Set focus on First Textbox

$(document).ready(function() {
       // focus on the first text input field in the first field on the page
        $("input[type='text']:first", document.forms[0]).focus();
    });

Comments

0

You can try this

var $textboxes = $("input[type='text']")

Now, $textboxes is an array of jquery objects representing all textboxes on the page, so you can do something like

$.each($textboxes, function(index, obj) {
  // do something to check if this is the textbox that you are looking for...
});

Comments

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.