0

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);
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
Muhammad Kazim
  • 611
  • 2
  • 11
  • 26

4 Answers4

3

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);
}
M.Nabeel
  • 1,066
  • 7
  • 19
0

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);
}
Koby Douek
  • 16,156
  • 19
  • 74
  • 103
0

your example looks good.It will work 100%.

0
   $(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);
   } 
Rajat Masih
  • 537
  • 1
  • 6
  • 19