I am using Replit.
The functions are not running, only the "myfunction" in the function check runs. The rest don't run when I press the buttons. However, these functions work in the index, when I put them in a different script, it stops working.
Html script calling the functions
<button id = "check" onclick='check()'>Show answers</button>
<button id = "color" onclick="color()">check</button>
The annoying function in js that has ben bothering me for weeks...
let pg=0;
var answer;
let ants;
let qtitle;
let question;
let squestion;
function check()
{
switch(pg){ //different header number is fine but do '' BUT input box will still be there
case 0:
qtitle="What do you know?"
ants = ['calculations']
question=["Element Symbol that has the atomic number of... ","atomic mass of (round to nearest whole number)..."]
squestion=["1. 50","2. 2","3. 20","4. K"]
case 1:
ants = ["0","11","11","4","9","Be","8","8","8"]
question=["Sodium has 11 protons and an mass of 23. What is the...","An atom has an atomic# of 4 and 5 neutrons What is the...", "Oxygen has 8 electrons and a mass of 16"]
squestion=["charge","atomic#","#of electrons", "#of protons","Mass","element symbol", "#of protons", "atomic#", "#of neutrons"]
// ants = ["Sn ","He ","Ca ","39 ", "32 ","Sn ","He ","Ca",]
// question=["Element Symbol that has the atomic number of... ","atomic mass of (round to nearest whole number)..."]
// squestion=["1. 50","2. 2","3. 20","4. K"]
break;
case 2:
ants = ["Carbon", "Chlorine", "Bromine",'Br',"Li","Sc","2","8","8" ]
question=["Carbon", "Chlorine", "Bromine", "Helium",'Br',"Li","Sc" ]
squestion=[]
}
// var textBoxes = document.querySelectorAll('[id^=CO]');
// var textToWrite;
// for(var i in textBoxes){
// textToWrite = textBoxes[i].value;
// console.log(textToWrite)
// }
let lowAnts = [] //loop will place lower case values of ants in here
// if(ants.toLowercase())
for (let i= 0; i < ants.length; i++){
lowAnts[i] = ants[i].toLowerCase() ;
}
console.log(ants)
let text="";
let loopNum = 0;
myfunction();
function myfunction() {
console.log(ants.length);
for(let i = 0; i < ants.length; i++){
loopNum ++; //increase number of array by 1 each time
if(loopNum === 3){ //if it gets to 3, break and reset to 0, so it starts again
text += (i + 1) + "." + ants[i] + "<br>";
loopNum = 0;
}else{ //if it is not 3,(cant go over since it restarts everytime), then it will just do this, without breaking
text += (i + 1) + "." + ants[i] + " "+ " "+ " "+ " "
// "⋅ " ;
}
if(i==9){
loopnum=4
}
}
}
// }
// let text="";
// ants.forEach(myfunction);
// function myfunction(item, index) {
// text += (index + 1) + "." + item + "<br>";
// }
//can also be put at the bottom
document.getElementById("demo").innerHTML = text;
}
function color()
{
console.log("color")
input=document.querySelector(input[type=text])
for(i=0;i<5;i++)
{console.log("works")
}
}
Thanks, this problem has been driving me crazy over the past few weeks.
Related
I have coded the below piece of code which handle the number bigger than 999 and add a comma to it. For example 1,000 and 1,000,000. Wheare as once the number increase the comma will be placed in the correct position. I used DRY principle and I feel still there is another easy way to handle it.
Now, I want to know if there is much better way than that I did.
Waiting for your opinion.
Thanks.
function seperate_num_by_comma() {
var num = '199228754645.25',
withOutComma = num.split('.'),
addNewCommaAfter = 3,
x = withOutComma[0].length % addNewCommaAfter,
lenOfWithOutComma_0 = withOutComma[0].length,
length_1 = withOutComma[0].length - x,
starter = 0,
wholeNumber = ' ';
for (var i = 0; i < lenOfWithOutComma_0; i++) {
function run_first_func() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter);
};
function run_second_fun() {
wholeNumber += withOutComma[0].substr(starter, addNewCommaAfter) + ",";
starter += addNewCommaAfter;
length_1 -= addNewCommaAfter;
};
if (x > 0) {
if (length_1 == 0) {
run_first_func();
break;
} else if (wholeNumber == ' ') {
wholeNumber += withOutComma[0].substr(starter, x) + ",";
length_1 -= addNewCommaAfter;
starter = x;
} else {
run_second_fun();
}
} else if (x == 0) {
if (length_1 == 3) {
run_first_func();
break;
}
run_second_fun();
}
}
console.log(wholeNumber + '.' + withOutComma[1]);
}
seperate_num_by_comma();
One Line:
165B minified version (no IE): seperate_by_comma=t=>(x=(""+t).split("."),z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|"),x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length),x.join("."))
OR 180B, IE-friendly: seperate_by_comma=function(t){x=(""+t).split(".");z=x[0].replace(/((\d{3})*?)(\.|$)/,"|$1").split("|");x[0]=z[0]+z[1].replace(/(.{3})/g,",$1").slice(!z[0].length);return x.join(".")}
Explanation:
seperate_num_by_comma = function(number){//12345678.9
var str = String(t);
var withoutDot = str.split("."); //["12345678", "9"]
var chunksOfThree = withoutDot[0].replace(/((\d{3})*?)(\.|$)/,"|$1");//"12|345678"
chunksOfThree = chunksOfThree.split("|");//["12", "345678"]
chunksOfThree[1] = chunksOfThree[1].replace(/(.{3})/g,",$1") //",345,678"
if(chunksOfThree[0].length==0){
chunksOfThree[1] = chunksOfThree[1].slice(1); //Fix for specific cases
}
withoutDot[0] = chunksOfThree[0] /*"12"*/ + chunksOfThree[1] /*",345,678"*/
return withoutDot.join(".") //"12,345,678.9"
}
var checkErrors = 0;
// Check for mistakes function
function yourResult() {
let checkErrors = 0;
let textEnterd = testArea.value;
let orginTextMatch = originText.substring(0, textEnterd.length);
if (textEnterd.length == originText.length || textEnterd == originText) {
if (textEnterd != orginTextMatch) {
++checkErrors;
}
theResult.innerHTML **strong text** = "You did " + checkErrors + " mistakes.";
}
}
testArea.addEventListener('keyup', function() {
yourResult();
}, false);
// "return"
This is a test typing project, i am stuck at the yourResult function, i cant get the desire errors.
The main mistake is that the error count is reset after each stroke.
So put that outside and you can match the characters as they're typed.
It's not far off, so you can try this instead:
// Put check errors variable outside of the function to keep count between the key strokes
// Reset to 0 when starting the test over
let checkErrors = 0;
function yourResult(){
let textEnterd = testArea.value;
let charPos = textEnterd.length;
// Match the characters at their positions. If they don't match, add them up
if (charPos > 0 && textEnterd.charAt(charPos) != originText.charAt(charPos)) {
++checkErrors;
}
theResult.innerHTML = "You did " + checkErrors + " mistakes.";
}
EDIT: the issue was a typo, this should have been caught and is not a good question. Sorry about that
So I've been working on making one of my own projects in JS, and it involves lots of buttons. I have one button (The one with the ID of "firstbuildmulti1") which should run the function "build1multi1" But I don't think it is doing that. I've looked over it multiple times and I'm not sure why it won't work. Any help is appreciated! (Side note: the button only appears after you click the third building button, this is intentional). EDIT: I ran the code on here and it said:
{
"message": "Uncaught ReferenceError: b1m1cost is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 183,
"colno": 17
}
My code is:
//declare variables for points, multiplier, buy upgrade, b1 2 and 3 cost and count, make point updater
var points = 9999;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var b3cost = 2000;
var b3count = 0;
var b1m1cost = 1500;
var currentpoints = setInterval(pointupdate, 500);
//clicking on main button to add points
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
console.log();
}
}
//make logic for doubling addpoints
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
//logic for displaying first building upgrade
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
//displays total points
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
//what happens when you click first building button
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
var b1multi = 1;
var b1pps = b1count * b1multi;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1! Making " + b1pps + " points per second."
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
//display second building
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
//what happens when you click second building button
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
var b2multi = 1;
var b2pps = (b2count * 4) * b2multi;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2! Making " + b2pps + " points per second."
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
//display third building
var thirdbuild = document.getElementById("thirdbuild");
thirdbuild.style.display = "inline";
thirdbuild.innerText = "Building 3. Cost " + b3cost;
}
}
//what happens when you click third building button
function build3() {
if (points >= b3cost) {
points -= b3cost;
b3count++;
b3cost *= 1.10;
var b3multi = 1;
var b3pps = (b3count * 10) * b3multi;
document.getElementById("b3").innerHTML = "You have " + b3count + " of building 3! Making " + b3pps + " points per second."
thirdbuild.innerText = "Building 3. Cost " + Math.round(b3cost);
var build3add = setInterval(build3points, 1000);
//first building first multiplier
var firstbuildmulti1 = document.getElementById("firstbuildmulti1");
firstbuildmulti1.style.display = "inline";
firstbuildmulti1.innerText = "Building 1 x2 multiplier. Cost: " + b1m1cost + "."
}
}
//add points for build1
function build1points() {
points += 1;
}
//add points for build2
function build2points() {
points += 4;
}
//add points for build3
function build3points() {
points += 10;
}
//second x2, display multiplier
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
function build1multi1() {
if (points >= b1m1cost) {
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
<p>Click to get started!</p>
<!--Link to all CSS files -->
<link rel="stylesheet" href="buttons.css">
<link rel="stylesheet" href="displayscores.css">
<link rel="stylesheet" href="layout.css">
<!-- make all buttons -->
<button id="addpoints" onclick="addPoints()" background-color:red>Add points</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<button id="thirdbuild" onclick="build3()" style="display:none;">Building 3. Cost x</button>
<br>
<p><b>Upgrades:</b></p>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="firstbuildmulti1" onclick="build1multi1()" style="display:none;">Building 1 x2 multiplier. Cost x</button>
<!-- make a div around all paragraphs displaying stats and display them -->
<div class="displayscores">
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
<p id="b3"></p>
</div>
First things first, as discussed in the comments, anytime you're stuck with the code, you can try using console.log() (If you're new to it, research a bit on using the Console for debugging)
function build1multi1() {
console.log("Entered function"); //If this is printed in console, that means the function is called
if (points >= b1m1cost) {
console.log("Entered condition"); //If this is not printed in console, it means condition points >= b1m1cost fails.
// console.log(b1m1cost); // You can check b1m1cost value in the console
// console.log(points); // You can check points value in the console
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
Problem 1 : b1m1cost is not defined
b1m1cost is not defined in the global scope. It is only declared in one of the functions. Hence, the condition inside build1multi1() must be failing.
Problem 2 : Can't read property style of null (Doesn't hide the button)
This is happening inside the build1multi1() function.
Which means var build1multi1 inside that function is null.
Which means document.getElementById("build1multi1"); is unable to find any element with id build1multi1.
If you want to hide the button then the id should be firstbuildmulti1 which is the id for the button. So, change it to document.getElementById("firstbuildmulti1");
I have written a code so it can count the characters inside the text box. The countting is working as expected but the problem is every time i move the cursor any where in the text box to change a word or add a word as soon as i press the first character curor moves to the end of the text.
Could you please help me edit the code:
function GetCountSms() {
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
if ($('#SndSms_Message').val().length == 0)
CounterSmsLen = 0;
$('#SndSms_Count').html(' ' + CounterSmsLen + ' Characters' + UniCodestring + ' <br /> ' + Math.ceil(CounterSmsLen / Countsms) + ' Sms');
countsmsnumber=Math.ceil(CounterSmsLen / Countsms);
}
PS.
I have added few lines of codes into the above code (i have mention in the code which lines are new) and its working but the problem is the typing speed when i try to type something it takes more seconds to show than a normal typing. (its like when i stop typing computer still type for 3-4 seconds after i stop):
function GetCountSms() {
//NEW CODES PART 1
document.getElementById('SndSms_Message').addEventListener('input', function (e) {
var target = e.SndSms_Message,
position = SndSms_Message.selectionStart;
//End OF NEW CODE
ConvertGreek();
CounterSmsLen = $('#SndSms_Message').val().length;
GetAlhpa($('#SndSms_Message').val());
var i = 0;
while (i < String(Two).length) {
var oldindex = -1;
while (String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) > -1) {
//if ( String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i))) > -1){
CounterSmsLen += 1;
oldindex = String($('#SndSms_Message').val()).indexOf(String(String(Two).charAt(i)), oldindex) + 1;
console.log(i);
}
i++;
}
// NEW CODE PART 2
SndSms_Message.selectionEnd = position; // Set the cursor back to the initial position.
});
On my site I have a set of input buttons with sizes.
// input elements
<input type="button" value="S" class="pblI" />
<input type="button" value="M" class="pblI" />
<input type="button" value="L" class="pblI" />
// output element
<input type="text" id="sizeMaster" value="" />
The user can click these buttons to construct an assortment, for example size S/1, M/2, L/3. A click on size S adds S/1 to the assortment. Next click on S make it S/2 and so on.
I'm using it on a mobile site with Jquery Mobile, so I know I'm getting the 300ms delay click.
Still the script is awfully slow to exectute, so I'm wondering if someone can point me to any "performance enhancements" for the following:
// an array and defaults
var remSize = [],
remIndex = -1,
szString, remData, i;
// click listener
$(document).on('click', '.pblI', function () {
// when clicked, construct a new object ala {size=S;qty=1}
szString = "";
remData = {};
remData.size = $(this).find('input').val();
remData.qty = 1;
// loop through the array to see whether the size is already in there
for (i = 0; i < remSize.length; i++) {
// return index position of size (otherwise index stays on -1)
if (remSize[i].size == remData.size) {
remIndex = i;
break;
}
}
// if the size is not in the array push the new object into the array
if (remIndex == -1 || typeof remIndex == "undefined") {
remSize.push(remData);
} else {
// else increase qty of exisiting size by 1
++remSize[remIndex].qty;
}
// create input string to display for the user
$(remSize).each(function (i) {
szString = szString + remSize[i].size + "/" + remSize[i].qty + " ";
// this will output something like this: 34/1 36/2 38/1
});
// update input field
$('#sizeMaster').val(szString);
});
I don't know what exactly is slow, but you can do these parts a little bit faster:
for (i = 0; i < remSize.length; i++) {
// return index position of size (otherwise index stays on -1)
if (remSize[i].size == remData.size) {
remIndex = i;
break;
}
}
to
for (i=0,j=remSize.length;i<j;++i) {
// return index position of size (otherwise index stays on -1)
if(remSize[i].size === remData.size) {
remIndex = i; i = j;
}
}
and
$(remSize).each(function (i) {
szString = szString + remSize[i].size + "/" + remSize[i].qty + " ";
// this will output something like this: 34/1 36/2 38/1
});
to
for(i=0;i<j;++i) {
szString += remSize[i].size + "/" + remSize[i].qty + " ";
}
and
$('#sizeMaster').val(szString);
to
document.getElementById('sizeMaster').value = szString;
But i don't think this will make a big difference.
Edit: Of course you need to define "j" at the beginning.
You can remove some of the delay by listening for touchend rather than click
Here's an example - http://code.google.com/mobile/articles/fast_buttons.html