jeudi 29 janvier 2015

Combine 2 similar Functions which use IF Java script

I have created two functions that run a similar set of IF statements, one shows the cost of a game, the other its name. I have used "onclick" to display both values in my form. It all works but suffers from bloat. Is there a way to combine both functions to shorten the script?



function GameTitle() {
var textboxValue = document.getElementById("game_id").value;
var message;
if (textboxValue == 1) {
message = "Fantasy World";
} else if (textboxValue == 2) {
message = "Sir Wags A Lot";
} else if (textboxValue == 3) {
message = "Take a Path";
} else if (textboxValue == 4) {
message = "River Clean Up";
} else if (textboxValue == 5) {
message = "PinBall";
} else if (textboxValue == 6) {
message = "Ghost girl";
} else if (textboxValue == 7) {
message = "Dress Up";
} else if (textboxValue == 8) {
message = "Where is my hat?";
} else {
message = "Invalid ID";
}
document.getElementById("game_title").value = message;
}

//Display price of Game
function Cost() {
var textboxValue = document.getElementById("game_id").value;
var cost;
if (textboxValue == 1) {
cost = "0.99";
} else if (textboxValue == 2) {
cost = "0.99";
} else if (textboxValue == 3) {
cost = "1.99";
} else if (textboxValue == 4) {
cost = "1.99";
} else if (textboxValue == 5) {
cost = "3.99";
} else if (textboxValue == 6) {
cost = "3.99";
} else if (textboxValue == 7) {
cost = "1.99";
} else if (textboxValue == 8) {
cost = "1.99";
} else {
cost = "Invalid ID";
}
document.getElementById("cost").value = cost;
}

Aucun commentaire:

Enregistrer un commentaire