I need your help. I want to declare input field in variable outside function and the variable should work in function: for example
var name = $("#name").val();
function _testAlert()
{
alert(name);
}
I need your help. I want to declare input field in variable outside function and the variable should work in function: for example
var name = $("#name").val();
function _testAlert()
{
alert(name);
}
HTML
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<input type="text" id="name" class="name" value="nabeel"/>
JAVASCRIPT
var name ;
$(document).ready(function() {
name = $("#name").val();
_testAlert();
});
function _testAlert()
{
alert(name);
}
Decalring a variable outside a function, like you did: var name
, would scope it as "global". You can use it inside functions with no problem.
The problem is that you are not waiting for the document to load the input's value before assigning it to the name
variable.
Try this:
var name ;
$(document).ready(function() {
name = $("#name").val();
});
function _testAlert()
{
alert(name);
}
your example looks good.It will work 100%.
$(document).ready(function() {
var name =$("#mydemo").val();
_testAlert();
});
function _testAlert()
{
alert(name);
}
and another method id out side the document ready function
var name =$("#mydemo").val();
function _testAlert()
{
alert(name);
}