0

I need to get the value of inputScore currently held in the extractVariable function into the assignValue function (this function gives the value of inputScore to an Index.html page). I tried to store inputScore in a global object to solve scope issues, but inside assignValue the global.scoreValue variable is undefined. How can I get inputScore into assignValue please? New to programming - any help appreciated. Thanks.

global = {};


function extractVariable(inputScore) {

   global['scoreValue'] = inputScore;

};


function assignValue() { 

    document.getElementById("inputScore").value = global.scoreValue;

};

Thanks for everyone’s help. I am so close to solving what I need to do. The issue seems to be getting inputScore into the Index.html page. I should have posted all of my code in the first place. Apologies. index.html is a separate file, which has a link to the javascript file (Game.js). I have tested the link and it is working. When a button is pressed in Game.js, index.html loads, reads the assignValue function in Game.js, and inserts the players score (inputScore) into an input value in a form. At the moment all that is being inserted into the form is: enter image description here
I cannot figure out why it is not working. I have included code from both files below. Any help is once again appreciated.

Game.js code:

function extractVariable(inputScore) {

return inputScore;


};


function assignValue(inputScore) {  
     document.getElementById("playerScore").value = inputScore;

};



var CrystalRunner = CrystalRunner || {};

CrystalRunner.GameState = {

init: function() {
  //...code here
  }, 


create: function() {
 //...code here
  },  


 update: function() {  
//..code here
//check if the player needs to die
      if(this.player.top >= this.game.world.height) {
         this.gameOver();
      }
  },  


 gameOver: function(){

    //..code here

    this.updateHighscore();

    //..code here

   },


  updateHighscore: function(){
    this.highScore = +localStorage.getItem('highScore');


    if(this.highScore < this.myScore){
            this.highScore = this.myScore;

            this.inputScore = this.highScore; 


            this.submitScoreButton = this.game.add.sprite(this.game.world.centerX-135, this.game.world.centerY+100, 'submitScoreButton');

            this.submitScoreButton.events.onInputUp.add(function() {

                    window.location.href = "index1.php"; 

              }, this);

        extractVariable(this.inputScore);
      }


      localStorage.setItem('highScore', this.highScore);
  },


};

Index.html code:

<?php
require_once 'dbconnect.php';

?>
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Crystal Candy Game Login</title>

    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css"/>
    <link href="css/style.css" rel="stylesheet">


</head>


<body onload="assignValue(extractVariable())" class="bg"> 


    <div id="preloader">
        <div id="status">&nbsp;</div>
    </div><!--preloader-->


    <div class="wrapper">


        <div id="main">

        <!-- Form -->
        <form id="form-style" method="post" action="crystalhandle.php" autocomplete="off">


                    <div class="form-group"> 
                        <label class="header-text"><span>First Name</span></label>
                        <input class="form-control" type="text" id="name" name="username" placeholder="Name" title="Please enter your Firstname" required="">
                    </div>


                    <div class="form-group"> 
                        <label class="header-text"><span>Score</span></label>
                        <input class="form-control" type="tel" id="playerScore" name="score" value="" readonly>
                    </div>


                    <div class="w3ls-btn form-group">       
                        <div class="wthreesubmitaits">
                        <input type="submit" name="signup" id="reg" class="button" id="next1" value="Send" style="font-family: sans-serif; font-size: 17px; font-weight: bold;"
                        </div> 
                    </div>


        </form>


        </div>

    </div>

<div id="bodytext"></div>


     <script type='text/javascript' src='js/jquery-2.2.3.min.js'></script>
     <script type="text/javascript" src="js/phaser.min.js"></script>
     <script type="text/javascript" src="js/states/Game.js"></script>

         <script>
            $(window).on('load', function() {
            $('#status').fadeOut(); 
            $('#preloader').delay(350).fadeOut('slow'); 
            $('body').delay(350).css({'overflow':'visible'});


            })
    </script>

</body>


</html>

I have done the following changes, I think a solution is at hand. In Index.html I changed the following line by removing inputScore:

<body onload="assignValue(extractVariable())" class="bg"  >

In Game.js I find that if I hard code a value into the extractVariable function (see below), the hard coded value is passed into the value attribute of the <input> tag in Index.html which is what I want it to do. However, I still cannot figure out why this only works with a hard coded value?

function extractVariable(inputScore) {
  inputScore = 27; //hard coded value works. Why?
return inputScore; 

};


function assignValue(inputScore) {  
  console.log(inputScore); //this console.logs the hard coded value from 
  //extractVariable like it should do
     document.getElementById("playerScore").value = inputScore;

};
Steph
  • 147
  • 1
  • 14
  • *"but inside assignValue the global.scoreValue variable is undefined"* That would happen if `assignValue` is called **before** `extractVariable`. Since you are not providing a [mcve], there is not much we can do to help. The code you posted so far is fine. – Felix Kling Dec 13 '18 at 08:23
  • add your html too, seems to be working with your current code. – Just code Dec 13 '18 at 08:23
  • 1
    Seems to be an [XY problem](http://xyproblem.info). Are these functions on different pages (as suggested by ”this function gives the value of inputScore to an Index.html page”)? – JJJ Dec 13 '18 at 08:24
  • 1
    Why just don't return that value from the `extractVariable` function? Then you can call it in the `assignValue` and use returned value. Or If its called anywhere outside use it returned value from there. – Anoush Hakobyan Dec 13 '18 at 08:25

5 Answers5

4

You can do this by returning the value from extractVariable and then passing it in as a parameter into assignValue:

function extractVariable(inputScore) {
  return inputScore;
};


function assignValue(inputScore) {
  document.getElementById("inputScore").value = inputScore;
};

assignValue(extractVariable(inputScore));
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64
1

You have to call or invoke extractVariable() inside assignValue()

var global = {};
function extractVariable(inputScore) {
   global['scoreValue'] = inputScore;
};
function assignValue() {
  extractVariable('test');
  document.getElementById("inputScore").value = global.scoreValue;
};
assignValue();
<input id="inputScore"/>

Though it is not necessary to use the variable in this case, you can simply return the value from the function:

function extractVariable(inputScore) {
   return inputScore;
};
function assignValue(input) {
  document.getElementById("inputScore").value = input;
};
assignValue(extractVariable('test'));
<input id="inputScore"/>
Giulio Bambini
  • 4,695
  • 4
  • 21
  • 36
  • 1
    If that was possible, then `extractVariable` should just return the value instead of using a global variable. – Felix Kling Dec 13 '18 at 08:24
1

Please use es6 and scoping with let - here is an example that works fine:

let scoreValue = 0;

function extractVariable(inputScore) {

    scoreValue = inputScore;

};

function assignValue() {

    console.log(scoreValue);

};

extractVariable(200);
assignValue();
  • 1
    Hello Sebastian, I appreciate all the help I can get. Thanks so much. Not sure who downvoted you, certainly wasn't me! – Steph Dec 13 '18 at 10:33
  • no Probs - since a few weeks downvotes increase --- programming is not a linear thing - you can reach your goal in a thousand ways. I try to give answers that match to the way you walked - for me - your case looks like a form-application so I would use a JS framework to handle all the stuff, writing classes and so on - but perhaps this is too much for the case you exactly need - so I tried to give you "hints" to solve your current architecture ... keep on coding ;) – Sebastian Felix Schwarz Dec 13 '18 at 10:50
  • 1
    and by the waym you can call function in a function the same way - when you use the right scoping: assignValue(extractVariable(200)); works ;) – Sebastian Felix Schwarz Dec 13 '18 at 10:53
  • Thanks Sebastian. I have edited my question by adding more code and have explained what I am trying to do more clearly. I should have done that in the first place. Nonetheless, I am much closer to solving this thanks to everyone's help so far. – Steph Dec 13 '18 at 11:32
1

I cannot figure out why it is not working.

The ids of HTML elements become global variables.

You have an element with id inputScore.

You are specifying that extractVariable should be called with inputScore as argument:

<body onload="assignValue(extractVariable(inputScore))" class="bg"> 

Thus you are trying to set the a DOM element to be the value of a text input. That cannot work. The string representation of a DOM element is exactly what you are seeing in your screenshot

console.log(document.createElement('span').toString());

It's not clear to me what you expect inputScore to refer to here. So the only suggestion I can give is to remove the onload handler.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • Thank so much Felix for your response. I had no idea about HTML element ids being global variables. I have changed the input id to `playerScore`. The `inputScore` parameter in the `assignValue` function being called `onload` in the`index.html` file is referencing the parameter used in `extractVariable(inputScore)` in the `Game.js` file. I do not know if this needs to be there though. index.html keeps telling me that `inputScore` is undefined. All I need is for the value returned to `extractVariable(inputScore)` in Game.js to be put into the value of the input tag in `index.html`. – Steph Dec 13 '18 at 19:03
  • Well, the browser is right, there is no variable `inputScore` in global scope when the page loads. What do you expect the value to be at page load? Or in other words: Which value do you want to show in the input field at page load. If the input field should *initially* be empty, just remove the call. – Felix Kling Dec 13 '18 at 21:06
  • Hi Felix, I have done some edits to my question explaining where I am now at. I have removed `inputscore` from the call in `index.js` as you suggested. Thanks for your help on that. If find that if I hard-code a value into `inputScore` in `Game.js` the code now works. If I don't hard code a value then it doesn't. Any idea why? `extractVariable` in `Game.js` is definitely getting a value because it console.logs one. – Steph Dec 14 '18 at 03:48
0

I have finally solved it. Here is the solution for anyone interested. I have included the Game.js code with comments to show what I did. Index.html remains as I edited it in the question. Thanks for everyone who helped.

    function extractVariable(inputScore) {

  inputScore = +localStorage.getItem('highScore'); //we then define inputScore again 
by getting the score stored on local storage

  return inputScore; 

};



function assignValue(inputScore) {  

     document.getElementById("playerScore").value = inputScore;

};



var CrystalRunner = CrystalRunner || {};

CrystalRunner.GameState = {

init: function() {

  },


create: function() {

  },   


update: function() {  

      if(this.player.top >= this.game.world.height && this.counter === 0 || 
 this.player.left <= 0 && this.counter === 0) {
         this.gameOver();
      }


  },     


  gameOver: function(){

          this.updateHighscore();



      var style = {font: '40px Arial', fill: '#fff'};
     this.add.text(this.game.width/2, this.game.height/4, 'GAME OVER', 
style).anchor.setTo(0.5);


      style = {font: '30px Arial', fill: '#fff'};
      this.add.text(this.game.width/2, this.game.height/4 + 50, 'High score: ' + 
this.highScore, style).anchor.setTo(0.5);

      this.add.text(this.game.width/2, this.game.height/4 + 80, 'Your score: ' + 
this.myScore, style).anchor.setTo(0.5);

      style = {font: '18px Arial', fill: '#fff'};
      this.add.text(this.game.width/2, this.game.height/4 + 120, 'Tap/click to play 
again', style).anchor.setTo(0.5);


      this.game.input.onDown.addOnce(this.restart, this);


    }, this);

    gameOverPanel.start();
    this.counter++;

  },


  restart: function(){

    this.game.state.start('Game');
  },

  updateHighscore: function(){
    this.highScore = +localStorage.getItem('highScore');


    if(this.highScore < this.myScore){
            this.highScore = this.myScore;

      localStorage.setItem('highScore', this.highScore);

      this.inputScore= +localStorage.getItem('highScore'); //this input.Score needs 
      //to get it's value from localStorage and not this.highScore


            this.submitScoreButton = this.game.add.sprite(this.game.world.centerX- 
   135, this.game.world.centerY+100, 'submitScoreButton');
            this.submitScoreButton.inputEnabled = true;
            this.submitScoreButton.fixedToCamera = true;

            extractVariable(this.inputScore); //call extractVariable

            this.submitScoreButton.events.onInputDown.add(function() {


                        window.location.href = "index1.php";


                  }, this);

            }

       },


};
Steph
  • 147
  • 1
  • 14