Abdul
Abdul

Reputation: 2120

Set Default Value for hidden field

I have a hidden field where i save a value when button is clicked. But on page load there is no value assigned to it. I need to know how to set default value of hidden field.

I am saving a string in hidden field when button is clicked and then access it in a JS function. But on page load the JS function return Undefined value error as the value of hidden field is not set on page load.

 function Confirm() {
 var nom = document.getElementById('hdNomValue').Value;
 if (nom != "") 
  {
      // logic here 
  } 
 }

Upvotes: 0

Views: 6823

Answers (5)

Sanjiv Dhakal
Sanjiv Dhakal

Reputation: 316

what are you using jquery or javascript, if u are using jquery you may try to use

var nom = $('#hdNomValue').val();

Upvotes: -2

ddb
ddb

Reputation: 2435

try to use this

if (nom !== "" && nom !== undefined) 

so, your code should be rewritten as below

function Confirm() {
     var nom = document.getElementById('hdNomValue').Value;
     if (nom !== "" && nom !== undefined)
     {
         // logic here 
     } 
}

Upvotes: 0

Noman
Noman

Reputation: 1487

you can also do this:

if (nom != "" || nom != undefined) {
    //Your Logic
}

Upvotes: 1

bhanu.cs
bhanu.cs

Reputation: 1365

Here for only text,password fields in html only you can give a default value attribute .But in the case of html

<input type="hidden" value="">

element the value would not be assigned by default.

If you want to use a hidden field with a default value use a text field with the property of display:none like

<input type="text" style="display:none" value="Default">

Or else if you are determined to use the hidden element only then you can go for a javascript based check solution like

 var nom = document.getElementById('hdNomValue').Value;
if (nom != "" || nom != undefined) 
  {

  } 

Upvotes: 0

Sachin
Sachin

Reputation: 40970

You can simply try with this

function Confirm() {
    var nom = document.getElementById('hdNomValue').Value;
    if (nom) {
        // logic here 
    }
}

So if(nom) will return true only when it has non-blank value. It'll return false if it is "" or undefined

Now the next thing, you need to make sure about the Id of the element. If you are using the asp.net hidden field with runat="server" then Id would be different than what are you expecting. So to make sure that Id remains same as you've given in asp.net markup, use ClientIdMode="Static"

Upvotes: 2

Related Questions