0

This is my code:

// user control
<asp:CheckBox ID="chbGenerali" runat="server" />

// js
var prova = $find("chbGenerali");
console.log(prova.checked);

but I get TypeError: prova is null. It should be a sort of:

document.getElementById("<%=chbGenerali.ClientID%>")

isn't it?

Do I need to enable somethings

markzzz
  • 47,390
  • 120
  • 299
  • 507
  • 4
    Look at the generated html code, that will help you see what the id is on the client side. – OlliM May 29 '13 at 13:01
  • @OlliM: `ContentPlaceBody_Registrazione1_chbGenerali` yes it is the input type checkbox :O – markzzz May 29 '13 at 13:01
  • According to this SO answer, $get() is shorthand for document.getElementById(), $find() is slightly different. http://stackoverflow.com/questions/7411056/in-microsoft-ajax-what-exactly-does-find-do – Jason P May 29 '13 at 13:02
  • Already tried with `$get()`, I get the same TypeError – markzzz May 29 '13 at 13:03

2 Answers2

4

ID's set compile time do not always equal the ID at runtime by default.

As you are using framework 4.0, you can use the ClientIDMode property on the control.

ClientIDMode="Static" 

Read this weblog article for more information about the ClientIDMode property.

Myrtle
  • 5,761
  • 33
  • 47
  • I prefer this answer as it fixes the underlying issue rather than (skilfully) working around it. – Stephen Kennedy May 29 '13 at 13:13
  • 1
    @StephenKennedy: CLientIDMode is easier to apply, but you will have to ensure yourself the uniqueness of your control in the page. For example, if this code appears in an ascx file, and if two instance of the control exists, this will lead to error – Steve B May 29 '13 at 13:15
4

Basically, the client side ID is not the same as the server side, because of the control tree handling. ASP.Net generate client side which are the combination of the hierarchy of the control Id's. This will ensure uniqueness of Ids.

For example, if your control is in the panel "pnlABC", and your checkbox is named "chkGenerali", the output clientID will be "pnkABC_chkGenerali". Extend this logic to the whole control tree to get the actual ID.

The simpliest way to solve your issue is to replace your code by:

var prova = $find("<%= chbGenerali.ClientID%>");

which will generate the actual client side ID at render time.

Steve B
  • 36,818
  • 21
  • 101
  • 174
  • This is indeed the better solution :) – Myrtle May 29 '13 at 13:09
  • 1
    @Aphelion: yours is also acceptable. If the control has a application wide behavior (exemple: unique search box in the header of all pages), it's perfectly acceptable to specify explicitely its ID by force the ClientIDMode. It actually depends on the usage of the control. – Steve B May 29 '13 at 13:11