jQuery: For loop if else and nth-child - javascript

for (i = 1; i < 24; i++){{
if(dices[i].value == 0) {
$('td div:nth-child(i)').addClass("zero-desktop")
} else if (dices[i].value == 1) {
$('td div:nth-child(i)').addClass("one-desktop")
} else if (dices[i].value == 2){
$('td div:nth-child(i)').addClass("two-desktop")
} else if (dices[i].value == 3) {
$('td div:nth-child(i)').addClass("three-desktop")
} else if (dices[i].value == 4) {
$('td div:nth-child(i)').addClass("four-desktop")
} else {
alert ("NOT WORKING")
}
}};
dices[i] is an array that displays 23 random numbers and there are 23 divs.
Each time dice[i].value equals to one of (0~4), class will be added to div and when it successfully adds a class to div, [i] will increment until it reaches the end number.
For some reason uncaught Error:syntax error, unrecognized expression: :nth-child error shows up.

The problem here is that you are literally inserting the character 'i' in your selectors instead of using the variable i. You should use string concatenation, like this:
for (i = 1; i < 24; i++) {
if (dices[i].value == 0) {
$('td div:nth-child(' + i + ')').addClass("zero-desktop")
} else if (dices[i].value == 1) {
$('td div:nth-child(' + i + ')').addClass("one-desktop")
} else if (dices[i].value == 2){
$('td div:nth-child(' + i + ')').addClass("two-desktop")
} else if (dices[i].value == 3) {
$('td div:nth-child(' + i + ')').addClass("three-desktop")
} else if (dices[i].value == 4) {
$('td div:nth-child(' + i + ')').addClass("four-desktop")
} else {
alert ("NOT WORKING")
}
}

Related

JS while loop doesnt stop at true

When you run this script it shows the HP for both of the pokemon when you press 1 and click enter it subtracts your attack hit points to the enemies hit points. When you or the ememy hits 0 or less than 0 hit points it is supposed to stop and just show who won in the console log. Instead it takes an extra hit to for it to show the message.
So if you are at -10 hp it takes one more hit.
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
if (!firstFight) {
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
}
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
}
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
Are there any ways I can make this code more efficient?
you can simply add another if condition to check whether life of the player is still greater then '0' or less then '0' in the same turn like this.
in this way you don't have to go for next turn to check for the players life plus it rids off the extra conditional statements...
if (fightOptions == 1) {
let attack1 = wildPokemon[0].hp -= pokeBox[0].attack.hp;
console.log(wildPokemon[0].hp);
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
}
if (!firstFight){
let attack2 = pokeBox[0].hp -= wildPokemon[0].attack.hp;
console.log(pokeBox[0].hp);
if (pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
}
}
}
The problem is, the points are getting subtracted after you check if they are equal to or below zero. Here is a way you can check before:
let firstFight = false;
while (!firstFight) {
let fightOptions = prompt("1. Fight, 2.Items, 3.Potions " + wildPokemon[0].name + ":" + wildPokemon[0].hp + " " + pokeBox[0].name + ":" + pokeBox[0].hp);
if (fightOptions == 1) {
wildPokemon[0].hp -= pokeBox[0].attack.hp;
if (wildPokemon[0].hp <= 0) {
console.log("You have won!");
firstFight = true;
} else {
console.log(wildPokemon[0].hp);
}
pokeBox[0].hp -= wildPokemon[0].attack.hp;
if (!firstFight && pokeBox[0].hp <= 0) {
console.log(wildPokemon[0] + " has killed you");
firstFight = true;
} else {
console.log(pokeBox[0].hp);
}
} else if (fightOptions == 2) {
} else if (fightOptions == 3) {
} else {
}
}
While loops stops when the condition is false, in you case, you set it to not false, it is not stopping because you did not explicitly determine it. There are 2 ways you can do.
1st:
while(!firstFight == false)
2nd:
var firstFight = true;
while(firstFight)
then set the firstFight to false inside your if else statements.

JS in page head section isn't excecuting

I have a script that handles a semi-complex contact form. The site is built using a website building platform called Duda and I think there may be timing issues as they load a bunch of scripts of their own. Anyway I'm getting a ReferenceError: price is not defined, error.
Price gets called onChange on inputs, for example:
<input value="Yes" name="dmform-9" type="radio" id="watch-me-hide" checked="checked" onchange="price()"/>
The script works sometimes, then other times not. Very frustrating. Does anyone know how to make sure that my functions get loaded in this situation?
Here is the whole script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
var counter = 0;
$(document).ready(function() {
$("input[type="radio"]").click(function() {
alert("here");
var ids = ["#occupiedBy", "#nameOccupied", "#phoneOccupied", "#mobileOccupied", "#emailOccupied"];
if($(this).attr("id") == "watch-me-hide" || $(this).attr("id") == "watch-me-show") {
if ($(this).attr("id") == "watch-me-hide") {
$("#show-me").hide();
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "watch-me-show"){
$("#show-me").show();
ids.forEach((id) => $(id).prop("required", true));
}
else {
}
} else if($(this).attr("id") == "hideShowInDepth-hide" || $(this).attr("id") == "hideShowInDepth-show") {
if ($(this).attr("id") == "hideShowInDepth-hide") {
$("#moreRooms").hide();
price(null);
ids.forEach((id) => $(id).prop("required", false));
}
else if ($(this).attr("id") == "hideShowInDepth-show"){
$("#moreRooms").show();
price(null);
ids.forEach((id) => $(id).prop("required", true));
}
}
else{
}
});
};
function price() {
var priceIncrement = 70;
var minimumPrice = "189.00";
var basic = document.getElementById("hideShowInDepth-hide");
var advanced = document.getElementById("hideShowInDepth-show");
var ids = ["numberAdditionalRooms", "numberLaundries", "bedrooms", "numberLounges", "numberDining", "numberKitchens", "numberBathrooms", "numberHallways", "numberGarages"];
if ((basic.checked == true) && (advanced.checked == false)) {
/* Get number of rooms for basic inspection */
var e = document.getElementById("bedrooms");
var numberOfBedrooms = e.options[e.selectedIndex].value;
if (numberOfBedrooms == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if ((numberOfBedrooms <= 3) && (numberOfBedrooms >= 1)){
document.getElementById("totalPrice").textContent = minimumPrice;
}
else if ((numberOfBedrooms <= 6) && (numberOfBedrooms >= 3)){
document.getElementById("totalPrice").textContent = "259.00";
}
else if (numberOfBedrooms > 6){
document.getElementById("totalPrice").textContent = "329.00";
}
else {
alert("Script error: Undefined number of bedrooms")
}
return false;
}
else if ((basic.checked == false) && (advanced.checked == true)) {
/* Get number of rooms for advanced inspection */
ids.forEach(logArrayElements);
if (counter == 0){
document.getElementById("totalPrice").textContent = "0.00";
}
else if (counter == 1){
document.getElementById("totalPrice").textContent = minimumPrice.toFixed(2);
;
}
else {
var money = ((counter * priceIncrement) + +minimumPrice) - +priceIncrement;
document.getElementById("totalPrice").textContent = money.toFixed(2);
}
counter=0;
return false;
}
else if ((basic.checked == false) && (advanced.checked == false)) {
alert("Script error: Neither checkbox is checked");
return false;
}
else if ((basic.checked == true) && (advanced.checked == true)) {
alert("Script error: Both checkboxes are checked");
return false;
}
else{
alert("Script error: Unknown error");
return false;
}
}
function logArrayElements(element, index, array) {
// alert("a[" + index + "] = " + element + " - " + value);
var e = document.getElementById(element);
var strUser = e.options[e.selectedIndex].value;
counter = +counter + +strUser;
}
</script>
watch-me-hide and watch-me-show are radio buttons that when changed they hide or show another section of the contact form to fill out, and make the inputs required or not.
hideShowInDepth-hide and hideShowInDepth-show are the same, but for another div section.
the price function updates the text in a span to reflect a new price when an input value has changed.
price() gets called onchange of dropdowns and radio buttons.
Any help appreciated.

Wrong value while getting last symbol in string in Javascript

I have a variable someText where number is stored. Depending on last number I need to add different text. So I convert someText into stiring, get string length in someTextLng and substract for the last symbol someTextLng.
document.write(lastChar + "<br/>"); in my example returns 7 - all ok.
Continuing with if and getting surprise - lastChar = 1. But why? Where is my mistake?
<script type="text/javascript">
var someText = 312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
document.write(lastChar + "<br/>");
if (lastChar = "1") {
document.write(lastChar+" Day")
}
else if (lastChar = "2") {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
</script>
Why not use the reminder operator % for the last digit?
var last = number % 10;
and later
if (last === 1) {
// do something
}
You need to use == to match the value of lastChar. To get the lastChar you can use reminder operator:
var lastChar = someText % 10;
if (lastChar == 1) {
document.write(lastChar+" Day")
}
else if (lastChar == 2) {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
If you want to check for something that equal to something else it's === not =
Your code should be like that
if (lastChar === "1") {
document.write(lastChar+" Day")
}
else if (lastChar === "2") {
document.write(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
:)
var someText = 312347;
someText= someText.toString();
someTextLng = someText.length-1;
var lastChar = someText.substr(someTextLng, 1);
console.log(lastChar + "<br/>");
if (lastChar == "1") {
console.log(lastChar+" Day")
}
else if (lastChar == "2") {
console.log(lastChar+" DayZ")
}
else {
alert ("Wuza");
}
Try this
<script type="text/javascript">
var lastChar = (312347 % 10).toString;
document.write(lastChar + "<br/>");
if (lastChar === "1") {
document.write(lastChar+" Day")
} else if (lastChar === "2") {
document.write(lastChar+" DayZ")
} else {
alert ("Wuza");
}
</script>

If statements and conditions

I am trying to confirm two different things in an alert box, if statement. The first is that the user pressed the yes button and the second is a user input value on the page. See the code below. I'm still pretty green, any help would be greatly appreciated.
var cMsg = "You are about to reset this page!";
cMsg += "\n\nDo you want to continue?";
var nRtn = app.alert(cMsg,2,2,"Question Alert Box");
if(nRtn == 4) && (getField("MV").value == 5)
{
////// do this
}
else if(nRtn == 4) && (getField("MV").value == 6)
{
/////then do this
}
else if(nRtn == 4) && (getField("MV").value == 7)
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
Your if...else syntax is incorrect. Correct syntax
if (condition)
statement1
[else
statement2]
Use correct syntax
if (nRtn == 4 && getField("MV").value == 5) {
////// do this
} else if (nRtn == 4 && getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4 && getField("MV").value == 7) {
/////then do this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
instead of
if (nRtn == 4) && (getField("MV").value == 5) {
////// do this
} else if (nRtn == 4) && (getField("MV").value == 6) {
/////then do this
} else if (nRtn == 4) && (getField("MV").value == 7) {
/////then do this
} <=== Remove this
} else if (nRtn == 3) {
console.println("Abort the submit operation");
} else { //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}
you are trying to evaluate two different conditions that is:
"nRtn" // value returned from app.alert(cMsg,2,2,"Question Alert Box");
and: getField("MV").value.
However, the compiler will only process the first condition because the braces end there. You should make sure to enclose all conditions within one brace. Individual conditions can and by convention should be in separate braces too within the main brace.
The right way therefore should be:
if ((nRtn == 4) && (getField("MV").value == 5))
//notice the initial if (( and terminating ))
//You could have 3 conditions as follows
// if (((condition1) && (condition2)) && (condition3)))
{
////// do this
}
else if((nRtn == 4) && (getField("MV").value == 6))
{
/////then do this
}
else if((nRtn == 4) && (getField("MV").value == 7))
{
/////then do this
}
}
else if(nRtn == 3)
{
console.println("Abort the submit operation");
}
else
{ //Unknown Response
console.println("The Response Was somthing other than Yes/No: " + nRtn);
}

jQuery detecting changes on two elements using keyup()

HTML:
<form>
<input type="text" id="target" placeholder="example.com">
<input type="checkbox" name="http" id="http" value="http"> http://
</form>
<div id="possible-targets">
<h4>Possible matches: </h4>
</div>
JS:
var target_value;
$(window).load(function () {
$('#target').keyup(function () {
target_value = $('#target').val();
if (target_value == '') {
$('#target-match').remove();
} else if ($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if ($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if ($('#http').prop('checked')) {
if ($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
});
Here is a JSFiddle: http://jsfiddle.net/h2Uw4/
Now when I start typing in the text input field I can see a live change in the possible-targets div, but when I click on the http:// checkbox it still needs to type at least one more character in the text input field to make a live change and add another possible target.
I tried to use keyup() on both #target (the text input) and #http (the checkbox) but it didn't work:
$('#target, #http').keyup()
Create a function and pass it to event handlers.
Example Code
var yourFunc = function () {
//Your code
};
$('#target').keyup(yourFunc);
$('#http').change(yourFunc);
DEMO
As per #DavidThomas comments you can also use
$('#target, #http').on('change keyup', yourFunc)
DEMO 2
Try this
var target_value;
$(window).load( function() {
$('#target').keyup(function() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
});
$('#http').click(function(){
if ($('#target').val() !== "")
if (this.checked === true) {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#possible-targets').html('<h4>Possible matches: </h4><h4><span id="target-match-h">' + target_value + '</span></h4>');
}
});
});
You will have to execute the callback functionality when the checkbox's value is changed.
please update the js as :
var target_value;
$(window).load( function() {
$('#target').keyup(displayMatches);
$('#http').change(displayMatches);
});
function displayMatches() {
target_value = $('#target').val();
if(target_value == '') {
$('#target-match').remove();
} else if($('#target-match').length == 0) {
$('#possible-targets').append('<h4><span id="target-match">' + target_value + '</span></h4>');
} else if($('#target-match').length != 0) {
$('#target-match').html(target_value);
}
if($('#http').prop('checked')) {
if($('#target-match-h').length == 0) {
$('#possible-targets').append('<h4><span id="target-match-h">http://' + target_value + '</span></h4>');
} else {
$('#target-match-h').html('http://' + target_value);
}
} else {
$('#target-match-h').remove();
}
}
updated fiddle

Categories

Resources