Reputation: 93
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
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
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