ghanshyam.mirani
ghanshyam.mirani

Reputation: 3101

Issue related to getting ClientID of asp controls in Javascript

I have asp.net webApplication having asp controls.

<asp:HiddenField ID="hdTime" runat="server" />

To Access above control in Javascript i have used $('#ContentPlaceHolder1_hdTime').val('AM');

it works fine in Mozila firefox but in InternetExplorer it takes $('#ctl00_ContentPlaceHolder1_hdTime').val('AM');

i have also tried

$('#<%= hdTime.ClientID %>')

but above syntext works only on .aspx page but when i use javascript.js file it doesn't find as $('#<%= hdTime.ClientID %>')

so how to access asp controls in .js file??

Thanks

Upvotes: 0

Views: 74

Answers (3)

Krish
Krish

Reputation: 688

You can use like this : <asp:HiddenField ID="hdTime" runat="server" ClientIDMode="Static" />

you can find the ID of the control, also important is to give ClientIDMode="Static"

var id = Document.getElememtById("hdTime").value;

or

var id = $("#hdTime").val();

Upvotes: 0

Ian Newson
Ian Newson

Reputation: 7949

Try using static client side ids:

http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode(v=vs.110).aspx

This issue is because the ids generated by webforms are dynamic, so you cannot hard code them. However, webforms 4 introduced static client side ids to solve the issue you are having.

For example, add this attribute to your control: ClientIDMode="Static", and then you can reference your control in JavaScript like this:

$('#hdTime')

If you can't use webforms v4 then you will have to put your JavaScript in the aspx page.

Upvotes: 1

Jameem
Jameem

Reputation: 1838

You can set Clientidmode="static" for the control..

<asp:HiddenField ID="hdTime" runat="server" Clientidmode="static"/>

Javascript:

//Accessing control in javascript

var abc=document.getelementbyid('hdTime').value;

Upvotes: 2

Related Questions