How to fire an Asp: HiddenField OnValueChanged event using jQuery?

I have this asp:hiddenField :

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

I would like to trigger an event with a changed value (server side) using jQuery:

 Protected Sub AuxHiddenField_Changed(ByVal sender As Object, ByVal e As System.EventArgs) Handles AuxHiddenField.ValueChanged 'some logic here End Sub 

I tried:

 $('#AuxHiddenField').val("Mohaha!!"); 

JQuery does not find an element and nothing happens. How to solve this?

+6
source share
2 answers

ASP.net uses an algorithm to generate ClientID . By default, it is based on a naming container in which the control is contained sequentially.

The identifier in the generated HTML is AuxHiddenField not AuxHiddenField , but something like ctl00_AuxHiddenField .

Or set ClientIDMode :

 <asp:HiddenField ID="AuxHiddenField" runat="server" ClientIDMode="Static" /> 

Or in jquery using the attirute selectors :

 $('input[id$=AuxHiddenField]') // id ends with AuxHiddenField 

I personally don't like the way <%= Field.ClientID %> do this because if your javascript is in a separate file, it will not be processed by asp.net.

Further reading:


Changing a value programmatically using javascript does not fire the change event, you must fire it manually:

 $('input[id$=AuxHiddenField]').val("any val").change(); // or .trigger('change'); 

In action here .


About the ValueChanged Event

Unfortunately, HiddenField does not have an AutoPostBack property (it makes sense after all).
I think that after changing the value you will have to start the postback programmatically.
If you are running ajax, use __doPostBack() , otherwise submit your form document.forms[0].submit() .

Another solution would be to replace the HiddenField with an invisible TextBox:

 <asp:TextBox runat="server" ID="mytextbox" Value="" Style="display:none;" AutoPostBack="true" OnTextChanged="mytextbox_TextChanged"></asp:TextBox> 

Changing the value programmatically will cause the event server to fail.
Please note that to hide the text field you should not use Visible="false , because then it does not appear in the final html, use the Style="display:none;" (css) property.

+18
source

To find the value:

 $('#<%= AuxHiddenField.ClientID %>').val("Mohaha!!"); 

However, setting a value using JavaScript never fires a change event, and I don't think hiddens support it.

0
source

Source: https://habr.com/ru/post/902752/


All Articles