SHERIN AS
SHERIN AS

Reputation: 93

How to pass value to the (function ( ) { })();when loading

I have input type hidden that contain a value 2

<input type="hidden" id="asd" value="2"/>

I need the value 2 so I am using following way

(function () {
   var div = $('#asd').val(); 
})();

but I get the value undefined how to solve it?

Upvotes: 0

Views: 59

Answers (2)

CD..
CD..

Reputation: 74176

Try:

$(function(){
    var div = $('#asd').val(); 
});

So your function will be executed when the DOM is fully loaded.

See a working example:

$(function() {
  var div = $('#asd').val();

  console.log(div);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="asd" value="2" />

Upvotes: 1

Samot
Samot

Reputation: 113

Using jQuery it is a good habit to put all of your code inside

$( document ).ready(function() {

});

because that prevent your code to begin before the rest of your DOM has been loaded.

So in your case your code should look like :

$( document ).ready(function() {
   var div = $('#asd').val(); 
});

Upvotes: 0

Related Questions