Function based on multiple image sources - javascript

I cannot seem to get this function to check multiple image sources on click and run a sound to work, is there something I am doing wrong?
function victory() {
if (document.getElementById("Image0").src == "0.jpg" &&
document.getElementById("Image1").src == "1.jpg" &&
document.getElementById("Image2").src == "2.jpg" &&
document.getElementById("Image3").src == "3.jpg" &&
document.getElementById("Image4").src == "4.jpg" &&
document.getElementById("Image5").src == "5.jpg" &&
document.getElementById("Image6").src == "6.jpg" &&
document.getElementById("Image7").src == "7.jpg" &&
document.getElementById("Image8").src == "8.jpg" &&
document.getElementById("Image9").src == "9.jpg")
{
document.getElementById("vic").currentTime = 0;
document.getElementById("vic").play();
}

It's working for me:
http://jsfiddle.net/29y5346m/1/
function victory() {
if (document.getElementById("Image0").src.indexOf("0.jpg") != -1)
{
document.getElementById("vic").currentTime = 0;
document.getElementById("vic").play();
}
}
Things you may have wrong:
"}" on the end is missing (for function victory())
image.src can have a route prefix for a given image, use indexOf instead. That way you search in the string for that name

Related

If else condition not working for string comparision in JS [duplicate]

This question already has answers here:
Check variable equality against a list of values
(16 answers)
Closed 1 year ago.
I have an if-else condition in js as below and I am expecting else condition to execute for the below logic, because the destination ID is in else if, but it always goes into the if condition. tried with == and === too.
What am I missing?
Note: The logic is to be supported in ie11
// destinationId is generated dynamically but i have assigned it to a variable for reference
Code 1
var fromId = "createNotification";
var destinationId ="detailedDescription";
if ((fromId == "createNotification") && (destinationId == "carNumber" || "setNumber")) {
//logic to execute
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || "detailedDescription")) {
//logic to execute
}
code 2
if ((["createNotification"].indexOf(fromId) > -1) && (["carNumber" || "setNumber"].indexOf(destinationId) > -1)) {
//logic to execute
} else if ((["createNotification"].indexOf(fromId) > -1) && (["faultRepBy" || "detailedDescription"].indexOf(destinationId) > -1)) {
//logic to execute
}
Change your condition as below:
if ((fromId == "createNotification") && (destinationId == "carNumber" || destinationId == "setNumber")) {
console.log("in if")
} else if ((fromId == "createNotification") && (destinationId == "faultRepBy" || destinationId == "detailedDescription")) {
console.log("in else if")
}

What is the best way to deal with multiple else if statements to increase speed in Google Apps Script?

I have a function that is supposed to unhide certain columns, but only if other filters that relate to the columns are not in use. Because there are 4 other filters that it needs to check to see if they are in use (either 'true' or 'false'), there are 16 possibilities that the function needs to run through.
I've used else if statements to accomplish this and it does work, but it is incredibly slow. I was wondering if there is a more appropriate way to deal with all the possible options that is faster.
This is the code I currently have (sorry if I've shown too much, not sure how much I need to include):
function Unfilter(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var numCols = sheet.getRange(1,3).getValue(); //gets the number of columns to loop through
var xRow = sheet.getRange(1,5).getValue() + 16; //gets the target row to run the blank check on
// check filter statuses
var nameShow = sheet.getRange(1,1).getValue();
var statusShow = sheet.getRange(2,1).getValue();
var dateShow = sheet.getRange(3,1).getValue();
var evidenceShow = sheet.getRange(4,1).getValue();
//loop through all target columns and unhide all columns that are not filtered
for (var i=10; i<=numCols; i++) {
if (sheet.getRange(xRow,i).getValue() == "") {
var catType = sheet.getRange(16,i).getValue();
if (nameShow == true && statusShow == true && dateShow == true && evidenceShow == true) {
sheet.showColumns(i)
} else if (nameShow == false && statusShow == true && dateShow == true && evidenceShow == true) {
if(catType !== "Name") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == true){
if (catType == "Date" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == false && evidenceShow == true) {
if (catType == "Status" || catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == true && dateShow == true & evidenceShow == false){
if (catType == "Status"|| catType == "Date") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == false && evidenceShow == true){
if (catType == "Evidence") {
sheet.showColumns(i);
}
} else if (nameShow == false && statusShow == false && dateShow == true && evidenceShow == false){
if (catType == "Date") {
sheet.showColumns(i);
}
}
//...etc for all 9 remaining possibilities
}
}
}
Even if you can't speed up showColumns() function you can significantly accelerate your script if you will use getValue() or getValues() as few as it possible. For example here you invoke these functions more than 7 times on the same sheet with static data. It's far from best practices:
You could use getValues() just once to get all data from the sheet and analyze the array instead. It would be much faster. getValue() / getValues() are quite slow and intentionally limited functions.
For example:
var data = sheet.getRange(1,1,10,10).getValues(); // get the array
var numCols = data[0][2];
var xRow = data[0][4] + 16;
var nameShow = data[0][0];
var statusShow = data[1][0];
var dateShow = data[2][0];
var evidenceShow = data[3][0];
// etc
I think it will be about five seconds faster already.
And it will even more faster if you change getRange(xRow,i).getValue() to data[xRow-1][i-1] in the loop.

Changing input fields

I got a situation in which, I am validating input type using jquery.
I have html drop down list which contains different parameters("select:first-child").
I am trying validating input box based on these parameters for this I have written following code in jquery.
For example-
If I select "Quantity" then input box should take only numbers.
If I select "TradeDate" then input box should take date.
Now problem is ,when I select parameter which has type date , datepicker appears to select date.
But when I select any other parameter having type numbers ,input still showing datepicker.
So, Where I am wrong ,I want each time this validation
Here var type[1] contains type of parameter eg. float,date,char etc.
$("#cond_div").children("select:first-child").change(function(event){
var temp = $(this).val();
var type = temp.split("_");
$("#cond_div").children("input").on("keypress keyup", function () {
if (type[1].localeCompare("date") == 0) {
$(this).datepicker();
}
else if (type[1].localeCompare("float") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
else if (type[1].localeCompare("int") == 0) {
$(this).val($(this).val().replace(/[^0-9\.]/g, ''));
if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
event.preventDefault();
}
}
});
});
Once you've transformed an input with the .datepicker() creator, it stays that way until you destroy it by calling .datepicker("destroy") function.
SOLVED...
Instead of going with tricky logic ,found a simple way
$(document).ready(function () {
$("#cond_div").children("select:first-child").change(function (event) {
var temp = $(this).val();
var type = temp.split("_");
console.log("->" + temp);
console.log("->" + type);
$("#cond_div").children("input").val("");
$("#cond_div").children("input").datepicker("destroy");
if (type[1].localeCompare("date") === 0) {
console.log(type[1]);
$("#cond_div").children("input").datepicker();
} else if (type[1].localeCompare("char") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "text");
} else if (type[1].localeCompare("float") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
} else if (type[1].localeCompare("int") === 0) {
console.log(type[1]);
$("#cond_div").children("input").attr("type", "number");
}
});
});

Make players take turns playing tic-tac-toe in JavaScript

I just picked up JavaScript and want to make my tic-tac-toe game object-oriented. Right now I'm having trouble making my players take turns. Below I've made a global variable turn that starts off as true, then alternates between true and false as a player clicks on the board. The HTML is not provided here, but each grid in the 3x3 board is a form.
If turn === true, it should be player_1's turn, and player_2 otherwise, but it isn't working. Any ideas on what I should be doing to get it right? I understand that the "if...else if" statement at the bottom runs only once, which is why it isn't working. Any ideas on what and where my conditional statement should be for it to work?
$(document).ready(function() {
var turn = true;
var Player = function(id,symbol){
this.symbol = symbol;
this.id = id;
function playerMove(player){
$("#tictac").on("click", function(event){
event.preventDefault();
var $button = $(event.target);
$button.val(symbol);
turn = turn ? false : true;
console.log(checkIfWinner());
console.log("turn:"+turn);
})
};
this.playerMove = playerMove;
function checkIfWinner(player) {
var $board = $("#tictac").children();
if ($board.find("#cell0").children().val() == symbol &&
$board.find("#cell1").children().val() == symbol &&
$board.find("#cell2").children().val() == symbol)
return true;
if ($board.find("#cell2").children().val() == symbol &&
$board.find("#cell5").children().val() == symbol &&
$board.find("#cell8").children().val() == symbol)
return true;
if($board.find("#cell0").children().val() == symbol &&
$board.find("#cell3").children().val() == symbol &&
$board.find("#cell6").children().val() == symbol)
return true;
if ($board.find("#cell0").children().val() == symbol &&
$board.find("#cell4").children().val() == symbol &&
$board.find("#cell8").children().val() == symbol)
return true;
if ($board.find("#cell2").children().val() == symbol &&
$board.find("#cell4").children().val() == symbol &&
$board.find("#cell6").children().val() == symbol)
return true;
if ($board.find("#cell3").children().val() == symbol &&
$board.find("#cell4").children().val() == symbol &&
$board.find("#cell5").children().val() == symbol)
return true;
if ($board.find("#cell6").children().val() == symbol &&
$board.find("#cell7").children().val() == symbol &&
$board.find("#cell8").children().val() == symbol)
return true;
if ($board.find("#cell1").children().val() == symbol &&
$board.find("#cell4").children().val() == symbol &&
$board.find("#cell7").children().val() == symbol)
return true;
return false;
}
this.checkIfWinner = checkIfWinner;
};
var startGame = function(player_1,player_2){
this.player_1 = player_1;
this.player_2 = player_2;
setMessage('<p>'+ player_1.symbol + ' starts the game</p>');
function setMessage(msg){
$("#message").html(msg);
};
};
var player_1 = new Player(1,"X");
var player_2 = new Player(2,"O");
var game = new startGame(player_1,player_2);
if (turn === true){
game.player_1.playerMove();
}
else if (turn === false){
game.player_2.playerMove();
}
game.player_1.playerMove();
});
This is not enough:
if (turn === true){
game.player_1.playerMove();
}
else if (turn === false){
game.player_2.playerMove();
}
You have to negate turn. Also, you can simplify the if ... else conditions:
if (turn) {
game.player_1.playerMove();
} else {
game.player_2.playerMove();
}
turn = !turn; // Negate the value to alternate moves.
You can write the player move even more succinctly, if you wish:
game['player_' + (turn ? '1' : '2')].playerMove();
Don't forget to put the player moves inside a loop of some kind:
while (true) {
// Make the player move.
// Check if the game is over.
// Has the player won? Is the board full? Display an appropriate message.
if (gameOver) {
break; // Break out of the loop if the game is over.
}
turn = !turn;
}

missing parenthesis error in javascript

I am using this function:
function sel_test(e) {
//alert(e.length-1);
var splitdata = e.split("d");
var newstr = e.substring(0,e.length-1);
dropcall = 1;
nodes = newstr.split(';');
o = 0;
if (nodes[0] == '1') o = nodes.shift();
for (i=0;i<nodes.length;i++) {
e = nodes[i];
var ul = document.getElementById(e);
if (icons) var img = document.getElementById(e+'i');
if (ul) {
if (((ul == 'none') AND (ul.style.display == 'none')) OR (ul.style.display == '')) {
ul.style.display = 'block';
} else if (!o) {
ul.style.display = 'none';
}
}
}
javascript is giving me an error of missing parenthesis:
if (((ul == 'none') AND (ul.style.display == 'none')) OR (ul.style.display == '')) {
what this the correct way of doing this.
You should be using && and || instead of AND and OR.
Shouldn't you?
Try this:
if (((ul == 'none') && (ul.style.display == 'none')) || (ul.style.display == ''))
JavaScript has an AND operator, but it isn't the word AND, it is && (also &, for a bitwise and). Similarly, rather than OR you want || (or | for bitwise).
Note that your ul variable will never be equal to the string 'none' - the return from document.getElementById(e) will always be either the matching DOM element, or null if no element has the supplied id.
Further reading: Logical Operators (and you should read it, because && and || don't always return true or false and MDN explains this).
You are also missing the closing right squiggly for the function.

Categories

Resources