Reputation: 27
I am using a switch statement to taken input data from an HTML text-box.
Thus far, it has been successful.
My next step is the following: if the user enters the number 20, I would like to input new data into a variable called "coordinates" so it may be used throughout the program.
So far, I am unable to use data from the variable "coordinates". Any suggestions?
switch(Number($('#inputdata').val())){
case 20:
var coordinates = {
latt1: 12,
lngg2: 34
}
break;
}
Upvotes: 0
Views: 89
Reputation: 802
I would argue that declaring the variable outside the switch and assign it is not a good idea, in the long run it can make thing harder to debug.
I would make a function that return the desired value and assign it to coordinated
function inputToCoordinate (inputValue) {
switch(inputValue) {
case 20:
return {
latt1: 12,
lngg2: 34
}
// ...
}
}
var input = $('#inputdata').val();
var coordinates = inputToCoordinate(parseInt(input, 10))
Also I'm not a big fan of switch statement, but that is another discussion.
Upvotes: 0
Reputation: 1616
You need to have your variable outside the switch statement. I would think about putting it in a closure like so:
function getCoordinates(element){
var coordinates = {};
// the closure is an immediately invoked function
// that sets the coordinates variable according to
// to the switch statements;
var coord = function(){
switch(parseInt(element.val()))
// case statements
coordinates = {"latt1":12,"lngg2":34};
}();
// ^^ means run this function now
return coordinates;
}
Then you can just assign the return of the outer function to a variable.
var c = getCoordinates($('#inputdata'));
The benefits here are that you don't pollute the global namespace with a global variable, your coordinates variable is private data, and you can easily modify the function params if you don't want to have a ton of switch statements.
Upvotes: 0
Reputation: 723
you need to save this input data into your coordinate variable
var coordinates = {
latt1: Number($('#inputdata').val()),
lngg2: 34
}
Upvotes: 0
Reputation: 16587
Make your variable global?
var coordinates;
switch(Number($('#inputdata').val())){
case 20:
coordinates = {
latt1: 12,
lngg2: 34
}
break;
}
Upvotes: 1