javascript having issue with indexOf [closed] - javascript

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 7 years ago.
Improve this question
So i have a html page with a guess my word game. but when i enter my first if statement with the variable FinalGuess for the indexOf it breaks, where as where i use SecretWord the page works but the function doesnt. any ideas?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Guessing Game</title>
<script type="text/javascript" >
/* <![CDATA[ */
var SecretWord = "compaq";
var GuessInput = document.forms[0].Guess.text;
var FinalGuess = GuessInput.toLowerCase();
var firstLetter = false;
var b = false;
var c = false;
var d = false;
var e = false;
var f = false;
function checkLetter() {
if (SecretWord.indexOf('c') >= 0) {
firstLetter == true;
}
/*
if (userInput.indexOf('o') >= 0) {
b == true;
}
if (userInput.indexOf('m') >= 0) {
c == true;
}
if (userInput.indexOf('p') >= 0) {
d == true;
}
if (userInput.indexOf('a') >= 0) {
e == true;
}
if (userInput.indexOf('q') >= 0) {
d == true;
}
*/
if (firstLetter == false) {
var letter1 = "*";
} else {
var letter1 = "c";
}
if (b == false) {
var letter2 = "*";
} else {
var letter2 = "o";
}
if (c == false) {
var letter3 = "*";
} else {
var letter3 = "m";
}
if (d == false) {
var letter4 = "*";
} else {
var letter4 = "p";
}
if (e == false) {
var letter5 = "*";
} else {
var letter5 = "a";
}
if (f == false) {
var letter6 = "*";
} else {
var letter6 = "q";
}
var string = letter1 + letter2 + letter3 + letter4 + letter5 + letter6;
document.forms[0].word.value = string;
document.forms[0].Guess.value = "";
document.forms[0].Guess.focus;
alert(GuessInput);
}
/* ]]> */
</script>
</head>
<body onload="checkLetter();">
<form action="" >
Guess the word
<input type="text" name="word" id="word" /><br />
Enter text here
<input type="text" name="Guess" maxlength="1" />
<input type="button" name="Submit" value="Submit" onclick="checkLetter();" />
</form>
</body>
</html>

You have to replace :
firstLetter == true;
By :
firstLetter = true;
We use == for comparison, but when you want just to assign value use =.

Related

How to fix credit card input spacing

I researched this on stack overflow, tried different answers but nothing worked for me. Can someone fix the problem please.
function spacingFunction() {
let varNumber = document.getElementById('cardnumber');
position = varNumber.selectionEnd;
varNumber.value = varNumber.value.replace(/[^\dA-Z]/g, '').replace(/(.{4})/g, '$1 ').trim()
varNumber.selectionEnd = position += ((varNumber.value.charAt(position - 1) === ' ' && varNumber.value.charAt(length - 1) === ' ' && length !== varNumber.value.length) ? 1 : 0);
}
<input id="cardnumber" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" type="text" onkeydown="spacingFunction()">
I tried all fix examples from the site. Need solution
Your question was very unclear, but I believe that you asked to fix the spacing issue, here's a very good example on jsfiddle
input_credit_card = function(input)
{
var format_and_pos = function(char, backspace)
{
var start = 0;
var end = 0;
var pos = 0;
var separator = " ";
var value = input.value;
if (char !== false)
{
start = input.selectionStart;
end = input.selectionEnd;
if (backspace && start > 0) // handle backspace onkeydown
{
start--;
if (value[start] == separator)
{ start--; }
}
// To be able to replace the selection if there is one
value = value.substring(0, start) + char + value.substring(end);
pos = start + char.length; // caret position
}
var d = 0; // digit count
var dd = 0; // total
var gi = 0; // group index
var newV = "";
var groups = /^\D*3[47]/.test(value) ? // check for American Express
[4, 6, 5] : [4, 4, 4, 4];
for (var i = 0; i < value.length; i++)
{
if (/\D/.test(value[i]))
{
if (start > i)
{ pos--; }
}
else
{
if (d === groups[gi])
{
newV += separator;
d = 0;
gi++;
if (start >= i)
{ pos++; }
}
newV += value[i];
d++;
dd++;
}
if (d === groups[gi] && groups.length === gi + 1) // max length
{ break; }
}
input.value = newV;
if (char !== false)
{ input.setSelectionRange(pos, pos); }
};
input.addEventListener('keypress', function(e)
{
var code = e.charCode || e.keyCode || e.which;
// Check for tab and arrow keys (needed in Firefox)
if (code !== 9 && (code < 37 || code > 40) &&
// and CTRL+C / CTRL+V
!(e.ctrlKey && (code === 99 || code === 118)))
{
e.preventDefault();
var char = String.fromCharCode(code);
// if the character is non-digit
// OR
// if the value already contains 15/16 digits and there is no selection
// -> return false (the character is not inserted)
if (/\D/.test(char) || (this.selectionStart === this.selectionEnd &&
this.value.replace(/\D/g, '').length >=
(/^\D*3[47]/.test(this.value) ? 15 : 16))) // 15 digits if Amex
{
return false;
}
format_and_pos(char);
}
});
// backspace doesn't fire the keypress event
input.addEventListener('keydown', function(e)
{
if (e.keyCode === 8 || e.keyCode === 46) // backspace or delete
{
e.preventDefault();
format_and_pos('', this.selectionStart === this.selectionEnd);
}
});
input.addEventListener('paste', function()
{
// A timeout is needed to get the new value pasted
setTimeout(function(){ format_and_pos(''); }, 50);
});
input.addEventListener('blur', function()
{
// reformat onblur just in case (optional)
format_and_pos(this, false);
});
};
input_credit_card(document.getElementById('cardnumber'));
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input id="cardnumber" placeholder="e.g. 1234 5678 9123 0000" maxlength="19" type="text" onkeydown="spacingFunction()">
<script src="script.js"></script>
</body>
</html>

Switch statement to check if something is in an predefined aray

How do i use a switch satement to check if the number divided by a number in an array == to 0.
how ive done it befor this is by using if statements and if else stateents to check:
if (i % num[0] == 0) {output thingy}
if (i % num[1] == 0) {output thingy}
and have an array named num.
Here is my current code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FizzBuzz</title>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
}
</style>
</head>
<body>
<button onclick="plus()">+</button>
<button onclick="minus()">-</button>
<button onclick="zero()">0</button>
<h1>Number:</h1>
<h2 id="number">0</h2>
<h1>Value:</h1>
<h2 id="val">0</h2>
<script>
var output = "";
var val = document.getElementById("val");
var number = document.getElementById("number");
var i = 0;
function zero() {
i = 0;
number.innerHTML = (i);
output = "0";
val.innerHTML = (output);
}
function plus() {
i++;
thingy()
}
function minus() {
i--;
thingy()
}
function thingy() {
var num = [3, 5]; // The numbers to multiply
var out = ["Fizz", "Buzz"] // The outputs
number.innerHTML = (i);
output = "";
for (var i = 0; i < num.length; i++){
var number = num[i];
if (i % number == 0) {
switch (number[i]) {
case [0]:
output += out[0]
break;
case [1]:
output += out[1]
break;
}
if ( output == "" ) { output = i; }
val.innerHTML = (output);
}
}
</script>
</body>
</html>
You can use true as your switch condition.
Example:
switch (true) {
case (i % num[0] === 0) : output code; break;
case (i % num[1] === 0) : output code; break;
}
Also, it's worth noting that your structure here is possibly redundant:
if (i % number == 0) {
switch (i) {
case [0]: output += out[0]; break;
case [1]: output += out[1]; break;
}
}
It would be enough to have:
if (i % number == 0) {
output += out[i];
}

Chrome Extension Settings page [duplicate]

This question already has answers here:
Completely lost on how to save extension popup window content
(2 answers)
Closed 6 years ago.
I have this piece of code(thanks to Shah Abax Khan), and I wanted to make it a Chrome extension. I wrote a settings/options page, but it doesn't actually save the settings. Help?
Javascript:
var pretty_fied = false;
var isOn = localStorage.isOn;
var isCapFirst = localStorage.isCapFirst;
var firstLetterPerWord = localStorage.firstLetterPerWord;
function yay() {
if ($("#on").value == "on") {
isOn = true;
localStorage["isOn"] = true;
}
else {
isOn = false;
localStorage["isOn"] = false;
}
if ($("#first").value == "on") {
isCapFirst = true;
localStorage["isCapFirst"] = true;
}
else {
isCapFirst = false;
localStorage["isCapFirst"] = false;
}
if ($("#per").value == "on") {
firstLetterPerWord = true;
localStorage["firstLetterPerWord"] = true;
}
else {
firstLetterPerWord = false;
localStorage["firstLetterPerWord"] = false;
}
};
$('input, textarea').keyup(function () {
alert(isOn);
if (isOn) {
prev = true;
var value = $(this).val();
var altText = '';
for (num = 0; num < value.length; num++) {
if (num % 2 == 0)
altText += value[num].toUpperCase();
else
altText += value[num].toLowerCase();
}
$(this).val(altText);
}
});
And here's the HTML:
<!DOCTYPE html>
<html>
<head>
<title>Y.A.Y | Options</title>
<script type="text/javascript" src="/js/caps.js"></script>
</head>
<body>
<h1>Settings</h1>
<form>
<label>Enabled: </label>
<select id="on">
<option value="on">Yes</option>
<option value="off">No</option>
</select>
</br>
<label>First Letter:</label>
<select id="first">
<option value="on">Capital</option>
<option value="off">Lowercase</option>
</select>
</br>
<label>Change First Letter of Each </label>
<select id="per">
<option value="on">Word</option>
<option value="off">Sentence</option>
</select>
<button id="done" onclick="yay()">Save</button>
</form>
</body>
</html>
yay() is supposed to save the settings, but it doesn't.
In Chrome Extension you shouldn't use a LocalStorage. It's for websites.
Use Chrome Storage instead like this:
JavaScript:
var pretty_fied = false;
var isOn;
var isCapFirst;
var firstLetterPerWord;
getData()
function getData() {
chrome.storage.sync.get( function ( data ) {
isOn = data.isOn;
isCapFirst = data.isCapFirst;
firstLetterPerWord = data.firstLetterPerWord;
} )
}
function yay() {
isOn = $("#on").value == "on";
isCapFirst = $("#first").value == "on";
firstLetterPerWord = $("#per").value == "on";
chrome.storage.sync.set( {
isOn: isOn,
isCapFirst: isCapFirst,
firstLetterPerWord: firstLetterPerWord
} )
}

if statement not working when placed in the function [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I have a problem with my if statement that is tasked with checking the input fields and giving me a message that will say if my fields are empty. The problem is I wanted to put it inside of a function so that if the if statement is false it would automatically proceed on with the function and do the task it was meant to do.
As you can see almost all of the functions have the if statement in them.
(I'm making a calculator).
Oh, and please use this basic JavaScript as I did. My knowledge of JavaScript is still not very good and since I'm doing this for a school assignment I should probably use this type of codes.
I will post my code here:
<html>
<head>
<meta charset="utf-8"/>
<script>
function pozdrav()
{
alert("Unesite dva broja te odaberite željenu operaciju:");
}
function brisi()
{
var prvibroj = "";
var drugibroj = "";
var rezultat = "";
document.getElementById("prvibroj").value = prvibroj;
document.getElementById("drugibroj").value = drugibroj;
document.getElementById("rezultat").value = rezultat;
}
function boja(elem)
{
var elem = elem.style.color="red";
}
function staraboja(elem)
{
var elem = elem.style.color="black";
}
function promjena()
{
var rezultat="";
document.getElementById("rezultat").value = rezultat;
}
function plus()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj + drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function minus()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj - drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function mnozenje()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj * drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
function djeljenje()
{
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(prvibroj == "" || drugibroj == "")
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj / drugibroj;
document.getElementById("rezultat").value = rezultat;
}
}
</script>
</head>
<body onload="pozdrav()">
<h2>Kalkulator</h2>
<p>Prvi broj:</p>
<input type="text" id="prvibroj" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br />
<p>Drugi broj:</p>
<input type="text" id="drugibroj" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br />
<p>Rezultat:</p>
<input type="text" id="rezultat" onmouseover="boja(this)" onmouseout="staraboja(this)" onchange="promjena()" /> <br /> <br />
<input type="button" value="+" onclick="plus()"/>
<input type="button" value="-" onclick="minus()"/>
<input type="button" value="*" onclick="mnozenje()"/>
<input type="button" value="/" onclick="djeljenje()"/>
<input type="button" value="C" onclick="brisi()"/>
</body>
</html>
You are doing this:
var prvibroj = parseInt(document.getElementById("prvibroj").value);
which if document.getElementById("prvibroj").value is empty will set prvibroj to NaN.
Then you are comparing this variable as if it was a string:
if(prvibroj == "" || drugibroj == "")
but if the values are empty it's the same as if (NaN == "" || NaN == "") which will always evaluate to false (NaN is never equal to anything).
So one solution is to check for NaN instead of empty string. For example:
var prvibroj = parseInt(document.getElementById("prvibroj").value);
var drugibroj = parseInt(document.getElementById("drugibroj").value);
if(isNaN(prvibroj) || isNaN(drugibroj))
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}
else
{
var rezultat = prvibroj + drugibroj;
document.getElementById("rezultat").value = rezultat;
}
(and the same for all the functions)
Since you are converting your input value to integer
var drugibroj = parseInt(document.getElementById("drugibroj").value);
the value in drugibroj if the field is blank will be NaN, So you should check for Nan in you if condition instead of ""
if(isNaN(prvibroj) || isNaN(drugibroj))
{
alert("Za ispravan izračun, morate unijeti oba broja!");
}

HTML file won't show my javascript variable

I've written a javascript function with some variables, i've tried to test it to see if variables would show in my HTML document but they wont and i have no idea why. Specifically, i'm trying to insert variable currentScore which is set to 0 at the beginning, so it should show 0 in a textbox, but it doesnt appear there.
Here is my javascript :
var who = 0;
var decision = 0;
var diceOne = 0;
var diceTwo = 0;
var currentScore = 0;
player playerAI = new player;
player playerOne = new player;
document.getElementById('currentScore').value = currentScore;
function rollDice() {
diceOne = Math.round(6 * Math.Random() + 1);
diceTwo = Math.round(6 * Math.Random() + 1);
}
function mainFunction() {
playerAI.playing = true;
playerOne.playing = true;
while (playerAI.playing == true && playerOne.playing == true) {
makeMove();
}
}
function makeMove() {
if (who == 0) {
aiStrat();
game();
}
else {
game();
}
}
function game() {
if (decision == 1) {
rollDice();
if (diceOne != 1 && diceTwo != 1){
currentScore += diceOne + diceTwo;
decision = 0;
makeMove();
}
if (diceOne == 1 || diceTwo == 1){
currentScore = 0;
decision = 0;
who = 1 - who;
makeMove();
}
if (diceOne == 1 && diceTwo == 1) {
currentScore = 0;
if (who == 0) {
playerAI.totalScore = 0;
}
else {
playerOne.totalScore = 0;
}
decision = 0;
who = 1 - who;
makeMove();
}
}
if(decision == -1) {
if (who == 0){
playerAI.totalScore += currentScore;
playerAI.checkScore();
}
else {
playerOne.totalScore += currentScore;
playerOne.checkScore();
}
currentScore = 0;
decision = 0;
who = 1 - who;
}
}
function aiStrat() {
if (playerAI.totalScore < 60) {
if (currentScore < 30) {
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 60 && playerAI.totalScore < 80) {
if (currentScore < 20){
decision = 1;
}
else {
decision = -1;
}
}
if (playerAI.totalScore >= 80){
if (currentScore < 10) {
decision = 1;
}
else {
decision = -1;
}
}
}
var player {
var totalScore = 0;
var playing = true;
function checkScore() {
if (totalScore >= 100) {
playing = false;
}
};
};
And my HTML document is this:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="BigPig.css">
<script type="text/javascript" src="VorgurakendusedKD1\Vorgurakendused.js" ></script>
</head>
<body onload="javascript:mainFunction()">
<div class="centered" type="text/javascript">
<h1>BIG PIG</h1>
<button><input type="button" value="START FROM BEGINNING" onclick="mainFunction();">
<span></span></button>
<br>
<button><span>GREEN BUTTON</span></button>
<br>
<button><span>RED BUTTON</span></button>
<br>
<output class="textbox" type="text/javascript" id="currentScore">CURRENTSCORE:
</output>
<br>
<output class="textbox" type="text">CPU SCORE: </output>
<br>
<output class="textbox" type="text">PLAYER SCORE: </output>
<br>
<p>Player versus computer</p>
<br>
<p id="currentScore"></p>
</div>
</body>
</html>
Here: document.getElementById('currentScore').value = currentScore;you try to find an element before it has loaded, and that's why you can't assign a value to it.
Try putting document.getElementById('currentScore').value = currentScore; inside your onload-function, mainFunction()

Categories