Global Variables. This code is not working

csp-unit-5

#1

Hey,

I thought this code should work as surely the variables (although they are global) should still work if called within the event.

Whether the student should create them as local is another matter, but surely the code should still work? Or am I missing something?

var noun = getText(“titleFirstInputBox”);

var adjective = getText(“titleSecondInputBox”);

var verb = getText(“titleThirdInputBox”);

var finalMessage = ("Don’t use a " + adjective + " " + noun + "when " + verb);

onEvent(“titleSubmitButton”, “click”, function(){

setScreen(“resultScreen”);

setText(“resultTextBox”, finalMessage);

});

onEvent(“resultBackButton”, “click”, function(){

setScreen(“titleScreen”);

});


#2

Also had the same happen with other students too. So not just a localized problem.


#3

They can be global variables, but the assignment of the text input must happen inside the onEvent. As it stands now, the program assigns the variables and initializes them to the value of the text boxes, which when the program starts is blank.

Here’s a working Submit Button onEvent. I don’t see a good reason to make the variables global, so I made them local instead.

onEvent(“titleSubmitButton”, “click”, function(){

var noun = getText(“titleFirstInputBox”);

var adjective = getText(“titleSecondInputBox”);

var verb = getText(“titleThirdInputBox”);

var finalMessage = ("Don’t use a " + adjective + " " + noun + "when " + verb);

setScreen(“resultScreen”);

setText(“resultTextBox”, finalMessage);

});


#4

Thanks Jhall9. We can get the code to work if we adjust it.

I still do not see how the original code does not work.

Are you saying anything that uses getText has to be inside the onEvent? I thought only the setText had to be inside the onEvent.


#5

Yes, the getText needs to be inside an onEvent. Otherwise it gets the text when you initially run the program and nothing is there. The user hasn’t entered anything. The click of Submit button should trigger the program to getText and assign what is in those input boxes to the variables.

I suppose you could do an onEvent of the text input box changing for each text input box, but that seems messy. You only need to pull the information when the user clicks submit.