[javascript] jQuery access input hidden value

How can I access <input type="hidden"> tag's value attribute using jQuery?

This question is related to javascript jquery

The answer is


There's a jQuery selector for that:

// Get all form fields that are hidden
var hidden_fields = $( this ).find( 'input:hidden' );

// Filter those which have a specific type
hidden_fields.attr( 'text' );

Will give you all hidden input fields and filter by those with a specific type="".


There is nothing special about <input type="hidden">:

$('input[type="hidden"]').val()

Watch out if you want to retrieve a boolean value from a hidden field!

For example:

<input type="hidden" id="SomeBoolean" value="False"/>

(An input like this will be rendered by ASP MVC if you use @Html.HiddenFor(m => m.SomeBoolean).)

Then the following will return a string 'False', not a JS boolean!

var notABool = $('#SomeBoolean').val();

If you want to use the boolean for some logic, use the following instead:

var aBool = $('#SomeBoolean').val() === 'True';
if (aBool) { /* ...*/ }

To get value, use:

$.each($('input'),function(i,val){
    if($(this).attr("type")=="hidden"){
        var valueOfHidFiled=$(this).val();
        alert(valueOfHidFiled);
    }
});

or:

var valueOfHidFiled=$('input[type=hidden]').val();
alert(valueOfHidFiled);

To set value, use:

$('input[type=hidden]').attr('value',newValue);


Most universal way is to take value by name. It doesn't matter if its input or select form element type.

var value = $('[name="foo"]');

If you have an asp.net HiddenField you need to:

To access HiddenField Value:

$('#<%=HF.ClientID%>').val()  // HF = your hiddenfield ID

To set HiddenFieldValue

$('#<%=HF.ClientID%>').val('some value')   // HF = your hiddenfield ID

If you want to select an individual hidden field, you can select it through the different selectors of jQuery :

<input type="hidden" id="hiddenField" name="hiddenField" class="hiddenField"/> 


$("#hiddenField").val(); //by id
$("[name='hiddenField']").val(); // by name
$(".hiddenField").val(); // by class