简体   繁体   中英

Javascript returns undefined with asp.net master pages

I'm running into a bit of an issue. My JavaScript function returns "undefined" when using master pages. However, when I'm not using master pages, it works fine. Here is my code:

HTML:

<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text" onkeyup="GoToNextTextBox(this.id, 3, 'cphMainArea_txtPhoneNumberFirstThree')" /> 

The Javascript:

function GoToNextTextBox(CurrentTextBox, MaxCharLength, NextTextBox) {
    alert(CurrentTextBox.value);//pops up "undefined"
    if (CurrentTextBox.value.length == MaxCharLength) {
        NextTextBox.focus();
        NextTextBox.style.backgroundColor = '#FFFFFF';
    }

Again, this works fine when not using master pages. So I'm completely confused.

This is because, you are doing it wrong.

In GoToNextTextBox() , you are expecting a DOM element, but you are passing only its id.

DO this:

<input id="txtPhoneNumberAreaCode" class="TextBox" runat="server" type="text" 
onkeyup="GoToNextTextBox(this, 3, 'cphMainArea_txtPhoneNumberFirstThree')" /> 

When using master pages and user controls the rendered ID of your controls change, but there is a way to stop it.

Let's say you have a Textbox

<asp:Textbox id="txtName" runat="server"></asp:Textbox>

on a standard asp page, it's id will be as you expect, txtName Now you add a master page, called Site.Master. In your rendered html, the controls name is now different.

cntl1_Site_txtName

I might have the syntax of the new name a bit off, but you can view source and find it for yourself.

There is a way to control that though. There is a property on your page, ClientIDMode. If i remember correctly it has 3 or 4 options. Auto ID is default I believe.

If you set it to static for that page, then you will no longer get the verbose control IDs, they will be as you expect.

This can be a downfall when using things like Repeaters though. You will not have easy access to specific fields if they do not have the verbose ID

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