How in JavaScript get hidden field value by id, by name.

/ / 0 Comments

JavaScript gets hidden input value: Here in this article will learn how to get hidden field value in JavaScript. The hidden field <input type="hidden"> is not visible to the end-user, but is available on the webpage and can be view via View Source.

The hidden field allows developers to add some data, that cannot be seen by the user while submitting the form.

Here will see 2 ways to get hidden field values in javascript.


Steps to get hidden input value

  1. Add HTML Markup
  2. JS code to get hidden field value by Id.
  3. JS code to get hidden field value by name.

Add HTML Markup

As we want to access hidden field values, hence we add input type hidden field with some value and button tag. On the button click will alert the hidden field value.

Our HTML markup looks like as written below:

<form>
 <input type=hidden id="myHiddenInputId" name="myHiddenInputName" value="Welcome to codepedia" />
 <input type=button value="Get Hidden Value by Id" onclick="fnById()" />
 <input type=button value="Get Hidden Value by Name" onclick="fnByName()" />
</form>

JS code to get hidden field value by Id

Here we create a js function, and by using document.getElementById will select our hidden field by its Id, and with .value will get the hidden field value.

Our final Js code looks like as written below.

function fnById() {
    alert(document.getElementById("myHiddenInputId").value);
}

Here on button click our js function .ie fnById() get called and it alert the hidden field value.

View Demo

If we have Asp.net hidden field control, then on page load its id gets changed. And if we want to get hidden field value in javascript asp.net c#, then our code would be as written below.

function fnById() {
    alert(document.getElementById("<%= myHiddenInputId.ClientID %>").value);
}

JS code to get hidden field value by name

Here we create a javascript function i.e fnByName, and by using document.getElementsByName will select our hidden input filed, and with value we get the hidden field value.

Our final js code looks like as written below:

function fnByName() {
    alert(document.getElementsByName("myHiddenInputName")[0].value);
}

Note: With getElementsByName we have to mention index[0]

View Demo

Conclusion: Here we learn 2 ways to get hidden field values in javascript i.e by id, and by name. We also learn how to get hidden field values in javascript in the Asp.net C# project.

Other Reference:

Thank you for reading, pls keep visiting this blog and share this in your network. Also, I would love to hear your opinions down in the comments.

PS: If you found this content valuable and want to thank me? 👳 Buy Me a Coffee

Subscribe to our newsletter

Get the latest and greatest from Codepedia delivered straight to your inbox.


Post Comment

Your email address will not be published. Required fields are marked *

0 Comments