I-M-JM
I-M-JM

Reputation: 15950

jQuery access input hidden value

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

Upvotes: 204

Views: 492141

Answers (9)

Marcin Żurek
Marcin Żurek

Reputation: 151

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"]');

Upvotes: -2

Georg Patscheider
Georg Patscheider

Reputation: 9463

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) { /* ...*/ }

Upvotes: 1

Bruno Ferreira
Bruno Ferreira

Reputation: 89

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

Upvotes: 3

the_root
the_root

Reputation: 339

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

Upvotes: 6

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

You can access hidden fields' values with val(), just like you can do on any other input element:

<input type="hidden" id="foo" name="zyx" value="bar" />

alert($('input#foo').val());
alert($('input[name=zyx]').val());
alert($('input[type=hidden]').val());
alert($(':hidden#foo').val());
alert($('input:hidden[name=zyx]').val());

Those all mean the same thing in this example.

Upvotes: 397

kaiser
kaiser

Reputation: 22333

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="".

Upvotes: 18

Rodrigo Longo
Rodrigo Longo

Reputation: 1389

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

Upvotes: 4

Maxim Sloyko
Maxim Sloyko

Reputation: 15866

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

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

Upvotes: 4

Related Questions