After clicking start in this page, the value is lost.
What can I do, in order not to make the page reload itself?
<button onclick="start()">Start</button>
Start: this is called when the user clicks start on the setup screen
function start(reuse){
reuse = (typeof reuse === 'undefined') ? false : true;
//user input is read
numberOfQuestions = $("#amount").val();
time = $("#time").val();
showError = $("#showError").prop("checked");
showCorrect = $("#showCorrect").prop("checked");
fullscreen = $("#fullscreen").prop("checked");
//currentIndex is the index of current question in the list while in the quiz
currentIndex = -1;
//reset correct questions
correct = 0;
var pred = {place:1, time:2, other:3};
var _numberOfQuestions = 0;
if (reuse){
_data = filteredData;
} else {
_data = data;
}
//filteredData is the new list of question AFTER filtering it according to setup screen
filteredData = [];
$.each(_shuffle(_data), function(index, entry){
if ($("#ddcl-d1-i"+entry['pad']).prop("checked")){
if ($("#ddcl-d2-i"+pred[entry['pred']]).prop("checked")){
_numberOfQuestions++;
entry['a'] = _shuffle(entry['a']);
filteredData.push(entry);
}
}
if (_numberOfQuestions == numberOfQuestions) return false;
});
if (_numberOfQuestions == 0){
alert("No questions available");
return;
}
$("#quiz").show();
$("#setup").hide();
$("#finish").hide();
secondsLeft = time * numberOfQuestions;
doTimer();
nextQuestion();
if (fullscreen && screenfull.enabled){
screenfull.request(document.getElementById('container'));
}
}
I call Start with JavaScript.
I try to add autopostback ="false", but the outcome remains the same.
You can add type attribute to buttons, because they automatically submit forms.
<button type="button" onclick="start()">Start</button>
Related
I am wondering how I might be able to stop a button clicking if the function it is performing is running. Here is my JS code:
let money = 0;
let running = false;
function start(time, val) {
if (running == false) {
running = true;
console.log(running)
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout("start(" + time + ")", 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
} else if (running == true) {
console.log("Already Growing!");
};
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
What it does is start a progress bar (progress div). I want the button to alert a message saying already going or something like that.
The issue I am having is that it is jumping to the else if statement, and not running anything. The odd thing is that if I add a console.log into the middle of the if statement it works.
I think it is because the bar takes time to fill, it will never reach full if the user clicks it, because it will jump to the else if statement and cancel out the if function. (It only becomes false again after the bar reaches 100%)
Can anyone help? I am open to JS or Jquery (bit rusty on that tho).
Thanks
You need to prevent the button clicking, not the actual start function that you need to call it from by the timer. So it's better to separate these functions:
let money = 0;
let running = false;
// when clicking the button
function onClickButton(time, val) {
if(running) {
console.log("Already Growing!");
} else {
running = true;
start(time, val);
}
}
// timer function
function start(time, val) {
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(() => start(time), 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
}
#moneyValue::before {
content: 'Money: ';
}
<div id="moneyValue">0</div>
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="onClickButton(0, this.id)">Plant Seed</button>
Break out the logic into another function that does the updating. Button that starts it on one method and the logic that updates the UI in another.
let money = 0;
let running = false;
function start(time, val) {
if (running == false) {
running = true;
console.log(running)
runIt(time, val);
} else if (running == true) {
console.log("Already Growing!");
};
}
function runIt(time, val) {
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(function () {runIt(time); }, 30);
if (time == 100) {
bar.value = 0;
let id = val;
money++;
document.getElementById("moneyValue").innerHTML = money;
running = false;
}
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
<div id="moneyValue"></div>
You could add an additional parameter that tells the function that the call is coming from the loop, and doesn't need to check if it's already running.
let money = 0;
let running = false;
function start(time, val, isFromTimer) {
if (running == false || isFromTimer == true) { // add check
running = true;
console.log(running)
let bar = document.getElementById('progressBar1');
bar.value = time;
time++;
let sim = setTimeout(() => start(time, val, true), 30); // tell function it's from the timer
if (time >= 100) { // use more than or equal to instead
bar.value = 0;
let id = val;
money++;
//document.getElementById("moneyValue").innerHTML = money;
clearTimeout(sim);
running = false;
}
} else if (running == true) {
console.log("Already Growing!");
};
}
<progress id="progressBar1" value="0" max="100" style="width:150px;"></progress>
<button id="restart-button" class="plantBtn" onclick="start(0, this.id)">Plant Seed</button>
Why don't you just use some CSS manipulation in your function once it is clicked?
document.getElementById('restart-button').disabled = true;
Then at the end of your function:
document.getElementById('restart-button').disabled = false;
I'm new to coding and I built a Javascript calculator, but I can't get the display to clear after Im done with one calculation. Instead, the result of the first calculation goes into the input for the second calculation. For eg if I do 3+5 it'll give me 8, but if I then press 4, the display says 84 which is why its a problem. I can clear the screen via the clear button but it gets tedious after every single calculation. Thank you.
//select all the buttons
const buttons = document.querySelectorAll('button');
//select the <input type="text" class+"display" disabled> element
const display = document.querySelector('.display');
//add eventListener to each button
buttons.forEach(function(button) {
button.addEventListener('click',calculate);
});
//calculate function
function calculate(event) {
//current clicked buttons value
var clickedButtonValue = event.target.value;
if(clickedButtonValue === '=') {
//check if the display is not empty then only do the calculation
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
}
//if any key except "=" pressed again clear display
button.addEventListener('click',clearDisplay);
} else if (clickedButtonValue === 'C') {
//clear everything on display
display.value = "";
} else {
//otherwise concatenate it to the display
display.value += clickedButtonValue;
}
}
function clearDisplay(clickedButtonValue) {
if(clickedButtonValue !== "=") {
display.value = "";
}
}
You can have a variable that keeps track of the calculated state. If it has been calculated, clear the display and reset the state
var calculated = false;
function calculate( event ){
var clickedButtonValue = event.target.value;
if ( calculated ) {
display.value = "";
calculated = false;
}
if(clickedButtonValue === '=') {
if(display.value !== "") {
//calculate and show the answer to display
display.value = eval(display.value);
calculated = true;
}
}
// the rest of your logic here
}
I'm totally new in Javascript and i would like to build a chatbot using voice recognition and text to speech for a website. I made onoff button but it's not working.
I have tried:
while (value == "on") {
utterance.volume = 1;
}
also
if (value == "on") {
utterance.volume = 1;
} else {
utterance.volume = 0;
}
but still there is something wrong. Any help
function onoff(){
currentvalue = document.getElementById('onoff').value;
if(currentvalue == "on"){
document.getElementById("onoff").value="on";
}else{
document.getElementById("onoff").value="off";
}
return currentvalue;
}
function speak(string){
var soundonoff = onoff();
var utterance = new SpeechSynthesisUtterance();
utterance.voice = speechSynthesis.getVoices().filter(function(voice)
{return voice.name == "Alex";})[0];
utterance.text = string;
utterance.lang = "en-US";
if (soundonoff == "on"){
utterance.volume = 1; //0-1 interval
}else{
terance.volume = 0;
}
utterance.rate = 0.8;
utterance.pitch = 1; //0-2 interval
speechSynthesis.speak(utterance);
}
for this there is pause and resume method for window.speechSynthesis;
To stop :
speechSynthesis.pause(); // pauses utterances being spoken
see : pause
To Resume :
speechSynthesis.resume(); /// resumes utters ,
see resume
to Cancel (stop)
speechSynthesisInstance.cancel();
see cancel
according to your conditions, you can call these methods
for other methods see here
UPDATE: -
this is rough code, change according to your requirements
HTML :
<input type="checkbox" id="onoff" name="onoff" >On/Off<br>
<br/>
<input type="button" name="start" onclick="speak();" value ="start" > On/Off
<br>
Script :
<script>
var synth = window.speechSynthesis;
function speak(){
var utterThis = new SpeechSynthesisUtterance('My pleasure, poke me up if you need more info.'); //
synth.speak(utterThis);
}
//// on check box change event call this
$('#onoff').change(function() {
if($("#onoff").prop('checked') == true){
speechSynthesis.pause();
/// now I dont know you want to pause or stop, change it according to you
///requirment
}
else {
speechSynthesis.pause();
}
});
</script>
GITHUB - sample project
This my code:
$('.upgrade-strength').on('click', function () {
var strCount = $('#strId');
var points = $('#points');
var userId = $(this).attr('id');
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
return val*1-1;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
});
$.ajax("/upgrade-strength/"+userId,
{
});
});
<p>Available points: <strong><span id="points">{{Auth::user()->points}}</span></strong></p>
When I clicking the button the counter goes down till 0 and then button dissapears. But what happens more is, when the
points.html(function(i, val) reaches zero the button did not dissapear. You have to click one more time tu buttons dissapear. How to solve this ?
Try this it will work:
strCount.html(function(i, val) { return val*1+1 });
points.html(function(i, val) {
if(val*1>0){
val = val*1-1;
if(val == 0){
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
return val;
}else{
document.getElementById("strBtn").innerHTML = "";
document.getElementById("dexBtn").innerHTML = "";
document.getElementById("vitBtn").innerHTML = "";
document.getElementById("intBtn").innerHTML = "";
}
When val is 1, look at your code, and see what it's doing:
if(val*1>0) - I don't know why you keep using *1 but never mind that. 1 > 0 is true, so we're in the if block.
return val*1-1; - again, what's the deal with *1? Anyway, this returns 0.
The else block is not run.
The next time you click, if(val*1>0) is false so the else gets run, hiding the buttons.
Instead you should do something like:
If the value is 1, hide the buttons
Either way, return val-1;
I have simple function which checks if entered pin code is valid. But i don't know how to force for-loop to wait until i enter code again to check again it's validity.
So how it should be - i type PIN code, then click OK button and it checks whether it's correct (if it is, i can see my account menu; if it's not i have to type it again and i have 2 chances left). My code fails, because PIN when code is wrong program should wait until i type new code and press OK button again.
I tried setTimeout(), callback(), but it doesn't work. This is what i have - a function with for-loop that just runs 3 times (as it is suppose to, but not instantly) without giving a chance to correct the PIN code.
That's whole, unfinished yet, code: http://jsfiddle.net/j1yz0zuj/
Only function with for-loop, which checks validity of PIN code:
var submitKey = function(callback)
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
for (i=0; i<3; i++)
{
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (2-i);
callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
if (i=2) console.log("blokada");
}
}
else if (digitStatus == 1)
{
}
}
Your approach is wrong. You should not make the user wait!!! You need 2 more variables at the top of your programm pincount=0 and pininputallowed. Increase pincount in the submit key function by 1 and then check if pincount<3.
Here is a corrected version of your code.
http://jsfiddle.net/kvsx0kkx/16/
var pinCount=0,
pinAllowed=true;
var submitKey = function()
{
console.log("digit status" + digitStatus);
if (digitStatus == 0)
{
correctPIN = 1234;
var onScreen = document.getElementById("screen");
pinCount++;
if(pinCount >= 3) {
pinAllowed = false;
onScreen.innerHTML = "<br>blokada";
}
if(pinAllowed){
if (onScreen.innerHTML.slice(15, onScreen.innerHTML.length) == correctPIN)
{
setTimeout(accountMenu, 1250);
//break;
}
else
{
onScreen.innerHTML += "<br> Błędny kod PIN! Wpisz PIN ponownie. <br> Pozostało prób: " + (3-pinCount);
inputLength = 0;
document.getElementById("screen").innerHTML += "<br>Wpisz kod PIN: ";
//callback();
//cardInserted = function(function(){console.log("Ponowne wpisanie PINu");});
}
}
}
else if (digitStatus == 1)
{
}
}
You need to create much more variables to control your machine. Your add/delete digit function had conditions that were badly written and only worked if the text on the screen was short enough.
var inputLength = 0;
addDigit = function(digit){
//numKeyValue = numKeyValue instanceof MouseEvent ? this.value : numKeyValue;{
if (inputLength < pinLength) {
onScreen.innerHTML += this.value;
inputLength++;
}
//if (onScreen.innerHTML == 1234) console.log("PIN został wprowadzony");
},
delDigit = function(){
if (inputLength >= 0) {
onScreen.innerHTML = onScreen.innerHTML.slice(0, -1);
inputLength--;
}
};
If you want to empty the screen at any moment you can insert onScreen.innerHTML = ''; anywhere
ps: Thanks for the exercise and nice automat you made there.