Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Why can't I get the value of this hidden field?

I have a control...

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

Which renders as...

<input type="hidden" name="ctl00$cph_main$HiddenFieldServerDateTime" id="ctl00_cph_main_HiddenFieldServerDateTime" value="08/01/2010 10:54:11" 

Which I'm trying to get the value of using...

var serverDateTime = $("#HiddenFieldServerDateTime").attr('value');

So what's wrong?

I prefer this

var dateTime = $("[id$=_HiddenFieldServerDateTime]").val();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
406 views
Welcome To Ask or Share your Answers For Others

1 Answer

Because jQuery knows nothing about asp:HiddenField. It looks in the HTML structure where you have <input type="hidden" name="ctl00$cph_main$HiddenFieldServerDateTime" id="ctl00_cph_main_HiddenFieldServerDateTime" .... So there's no input with ID= HiddenFieldServerDateTime. There are a few ways to overcome this:

  • Use a css selector:

    <asp:HiddenField ID="HiddenFieldServerDateTime" 
                     runat="server" 
                     CssClass="SomeStyle" />
    

    with the following selector: var serverDateTime = $(".SomeStyle").val();

    CssClass is not an available class on the HiddenField class (and it doesn't have an Attributes collection, so you can't add it manually).

  • Use ClientID property:

    var serverDateTime = $("#<%= HiddenFieldServerDateTime.ClientID %>").val();
    
  • Wrap the hidden field in something you can select:

    <div class="date-time-wrap">
      <asp:HiddenField ID="..." runat="server" />
    </div>
    

     

    var serverDateTime = $('.date-time-wrap input[type=hidden]').val();
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...