0

I know it is very simple but I didn't get it right. Would someone help me. I need to get the hidden field value but it looks like I didn't get the element. The function is run because the alert box show 'run'. The alert in if statement didn't execute. I searched website Check if element exists in jQuery [duplicate] . I still find nothing what is wrong on my code. Would someone help me. Thanks.

There is my hidden field:

<asp:HiddenField ID="hdID" runat="server" value="hd"/>

The jQuery function:

function showMe() 
{
   alert('run');
   if ($('#hdID').length){
      alert( $('#hdID').val()); 
   } else {
      alert('no element'); 
   }
}
user819774
  • 1,456
  • 1
  • 19
  • 48

2 Answers2

2

In ASP.Net, runat="server" elements that do not have ClientIdMode="static" specified will have their IDs rewritten. As such, I'd expect that your HiddenField does not have an ID of hdID.

If this is not a repeated element (i.e. it is not in a Repeater, GridView, etc), then you can simply add ClientIdMode="static" to prevent this ID rewrite from occurring:

<asp:HiddenField ID="hdID" ClientIdMode="Static"  runat="server"  value="hd"/>

If this is a repeated element, then you cannot use this technique, as it will result in duplicate IDs. In such a case, you'd likely need to provide the surrounding intentions to figure out the best method. It could be using ClientIdMode="Predictable" to append an index, or simply using a class selector instead.


† It's also possible to override the default at the page or configuration level.

Tyler Roper
  • 21,445
  • 6
  • 33
  • 56
  • I tried to add ClientIdMode="static". It doesn't work. – user819774 May 22 '19 at 20:40
  • 1
    @user819774 As a last resort, try `Static`, case-sensitive. Otherwise there is something else at play: you'll have to right click your page, Inspect Element, and post the rendered HTML in your question instead of the ASP. – Tyler Roper May 22 '19 at 20:41
1

Like Tyler Roper mentioned, the id for runat="server" control is overwritten in DOM.

You can try (if you dont want to use ClientIdMode="Static")

alert($("#<%=hdID.ClientID%>").val());

Hope this helps

CMedina
  • 4,034
  • 3
  • 24
  • 39
rach
  • 669
  • 2
  • 8
  • 31