www.webdeveloper.com
Results 1 to 3 of 3

Thread: Variable not acting global

  1. #1
    Join Date
    Feb 2013
    Posts
    19

    Variable not acting global

    This shouldn't be so hard to help me with. This is the text game I'm making. I'm making it to learn Javascript. The variable name is declared outside the function but it's not acting like a global function. When you run the program the variable called name gets the users name in the function getname but goes blank when in the function tarien.
    What am I doing wrong?


    <html>

    <head>
    <title> Legend of the Dragonstone </title>


    <head>

    <body>
    <header>

    <script src = "http://ajax.googleapis.com/ajax/libs/jquery/1.6.3/jquery.min.js"> </script>

    <script>

    var name = "";


    $(document).ready(function() {

    function tarien() {

    $("header").append("<p>-= Terien =-</p>");
    $("header").append("<p>1. Enter Ye Old Weapon Smith</p>");
    $("header").append("<p>2. Enter Terien Armory</p>");
    $("header").append("<p>3. Enter Terien College of Proffesions</p>");
    $("header").append("<p>4. Fight in Arena</p>");
    $("header").append("<p>5. Enter Provision Store</p>");
    $("header").append("<p>6. Enter Black Pony Bar</p>");
    $("header").append("<p>" + name + ", Enter the number of your selection.</p>");

    // $("#button.click(function(){
    // $("p").hide();
    // var choice = $("#text").val();


    };

    function choosename() {

    $("header").append("<p>Please enter your characters name.</p>");

    $("#button").click(function(){
    $("p").hide();
    var name = $("#text").val();
    tarien();
    });
    };




    choosename();

    });

    </script>

    </header>

    <body>

    <input type="text" id="text">
    <p></p>
    <input type="button" value="ok" id = "button">

    </body>

    </html>

  2. #2
    Join Date
    May 2006
    Location
    Somewhere behind your screen
    Posts
    1,648
    replace var name = $("#text").val(); with name = $("#text").val();
    xxx: Guess Buddhist riddle: "What is the sound of one hand clapping?"
    yyy: facepalm

  3. #3
    Join Date
    Nov 2010
    Posts
    1,087
    but (based on the snippet shown) it would be better to keep that variable local and pass it as an argument to the tarien function:

    Code:
    function choosename() {
    
    // other stuff
    
    var name = $("#text").val();	
    tarien(name);
    }
    
    
    function tarien(nm) {
    
    // other stuff
    
    $("header").append("<p>" + nm + ", Enter the number of your selection.</p>");
    
    };

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles