Вопрос

I have a JavaScript function as follows:

function getWindowSize() {
   test.value = $(window).width();
   test2.value = $(window).height();
}

window.onresize = getWindowSize;

And in the ASP.NET page:

<input type="text" id="test2" value="Test"/>  
<input type="text" id="test" value="Test"/> 

This populates the fields when the screen size changes. When I put the page elements to have runat="server" they don't populate the screen size and cannot capture it server side.

Any suggestions?

Это было полезно?

Решение

You need to use ClientID if you have server tag. You are not currently using getElementById but you should to get the DOM element for better browser compatibility. If you have framework 4 and above you can use ClientIDMode and do it without ClientID

Javascript

function getWindowSize() {
       document.getElementById('<%= test.ClientID %>').value = $(window).width();
       document.getElementById('<%= test2.ClientID %>').value = $(window).height();
}
window.onresize = getWindowSize;

HTML

<input type="text" id="test2" value="Test" runat="server" />  
<input type="text" id="test" value="Test" runat="server" /> 

Другие советы

Since I cannot see the full code, I am going to assume ASP.NET replaces Id attributes with generated ones (something like _ctl$Container$test). As a workaround, if you use jQuery you can use CSS classes:

Javascript

function getWindowSize() {
       $('.WidthValue') = $(window).width();
       $('.HeightValue') = $(window).height();
}

HTML

<input type="text" id="test" value="Test" class="WidthValue" runat="server" /> 
<input type="text" id="test2" value="Test" class="HeightValue" runat="server" />  

Are you using Masterpages? Because when adding ASP.NET form controls using masterpages they use a prefix to identity the controls:

<input id="ctl00_ContentPlaceHolder1_txtName" class="textfield" type="text" name="ctl00$ContentPlaceHolder1$txtName">

Where ctl00_ContentPlaceHolder1_ is the prefix of the masterpage.

This can be the cause why your javascript function doesn't populate the fields. How do you identify your objects test and test2?

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top