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

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

asp.net - Jquery Hidden Field

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

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

1 Answer

0 votes
by (71.8m points)

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();
    

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...