Green Developer
Green Developer

Reputation: 187

Setting value to hidden fields not working with jQuery

I have an application that I am creating with Visual Studio 2013 and I'm running into some issues with assigning a value to a hidden field using jQuery. First let me say that I am assigning a value to a hidden variable because I cannot access the text value of a label in the .cs file directly so I have to assign the value of the label to the hidden input field so I can access it in the .cs file. I hope that makes sense.

Here are the hidden input fields that I have in my .aspx file:

  <input type="hidden" id="at" runat="server" />
  <input type="hidden" id="wt" runat="server" />
  <input type="hidden" id="att" runat="server" />
  <input type="hidden" id="wtt" runat="server" />
  <input type="hidden" id="gt" runat="server" />
  <input type="hidden" id="ah" runat="server" />
  <input type="hidden" id="wh" runat="server" />
  <input type="hidden" id="th" runat="server" />
  <input type="hidden" id="tah" runat="server" />
  <input type="hidden" id="twh" runat="server" />

Here is the function that I run any time a key is pressed:

<script src="Scripts/add-bid.js"></script>
<script type="text/javascript">
        $(document).ready(function () {
            $('input[type=text]').keyup(function () {
                calculateTotal();
            });
        });
</script>

Here is the code inside of the add-bid.js script, namely the calculateTotal function:

$("#at").val("100");
$("#wt").val("200");
$("#att").val("100");
$("#wtt").val("200");
$("#gt").val("600");
$("#th").val("42");

I have hard coded the values here for an example. I then go to retrieve the values of the hidden fields in my aspx.cs file, and they are all null. What am I doing wrong here? Any and all help is appreciated.

Upvotes: 0

Views: 790

Answers (2)

RickJames
RickJames

Reputation: 1755

Try the following:

$('#<%= at.ClientID %>').val("100");
$('#<%= wt.ClientID %>').val("200");
$('#<%= att.ClientID %>').val("100");
$('#<%= wtt.ClientID %>').val("200");
$('#<%= gt.ClientID %>').val("600");
$('#<%= th.ClientID %>').val("42");

Upvotes: 1

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93551

If you view source from a browser, you will probably find the IDs have been thrown away and replaced with generated ones. runat="server" causes it to use its own naming system.

Use ClientIDMode="Static" so that it will retain your original IDs.

e.g.

<input type="hidden" id="at" runat="server" ClientIDMode="Static" />

Reference: http://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode.aspx

Upvotes: 2

Related Questions