I'm learning JS and I'm trying to solve a coding challenge. I'm suppose to have an alert tell the user the total generator amount and the total watts when I input the parameters. Problem is the code reader says that I'm alerting more than one. What am I doing that is making the alert be called multiple times? Here was my first attempt:
function changePowerTotal(totalMW,genID,status,powerMW){
if(typeof(status) == "on" || typeof(status) == "ON"){
alert("Generator #"+genID+" is now on, adding "+powerMW+" MW, for a total of "+ (totalMW) +" MW!");
return false;
} else {
if(totalMW == 0){
alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (powerMW) +" MW!");
} else {
alert("Generator #"+genID+" is now off, removing "+powerMW+" MW, for a total of "+ (totalMW - powerMW) +" MW!");
}
return false;
}
}
changePowerTotal(0,2,"off",62);
I've also tried this:
function changePowerTotal(totalMW,genID,status,powerMW){
var genStatus = "";
if(status === "on"){
genStatus = " is now on, adding "
totalMW = totalMW + powerMW;
} else {
genStatus = " is now off, removing "
totalMW = totalMW - powerMW;
}
alert("Generator #"+genID+genStatus+powerMW+" for a total of "+totalMW+" MW!");
}
changePowerTotal(142,2,"off",62);
There is no problem in the function, I am guessing you per accidentally called it twice?
Please check if you did, there is no way this functions can alert twice. You must have made a mistake in calling it twice.
Thank you all for the help. I found the solution, here it is:
function changePowerTotal (totalMW, genID, genStatus,genMW){
var curStatus = " ";
var sumMW = 0;
if(genStatus === "off"){
curStatus = " is now "+genStatus+", removing ";
alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+totalMW+"MW!");
return totalMW + genMW
} else {
curStatus = " is now "+genStatus+", adding ";
sumMW = genMW + totalMW;
alert("Generator #"+genID+curStatus+genMW+" MW, for a total of "+(totalMW + genMW)+"MW!");
return totalMW + genMW
}
}
Related
I am trying to make a hangman game with an on-screen keyboard, there is alot more code then this but this is the specfic function that won't run. The HTML is just an example of one key, there are 27 including a space, all of them only run the wrong() function once.
Here's the HTML that executes the function:
<p class="key" id="q" onclick="q(); setTimeout(allclick, 200); setTimeout(wrong, 1000);" onmouseover="hoverq()" onmouseout="unhoverq()">Q</p>
And the script that should fire off everytime one of the keys is pressed but it doesn't.
<script>
function wrong(){
console.log("wrong()")
console.log(clickon)
if(wrong == length){
console.log("all wrong")
document.getElementById(clickon).setAttribute("onmouseover", " ")
document.getElementById(clickon).setAttribute("onmouseout", " ")
document.getElementById(clickon).setAttribute("onclick", " ")
document.getElementById(clickon).style.backgroundColor="red"
}else{
wrongcheck = 1
console.log(wrongcheck)
}
console.log("_____")
</script>
Edit:
This may help you understand this better.
var length = word.length;
function allclick(){
for(l = 0; l <= length; l++){
if(clickon == letter[l]){
if(clickon == " "){
document.getElementById("blank" + l).innerHTML = " "
document.getElementById("space").setAttribute("onmouseover", "")
document.getElementById("space").setAttribute("onmouseout", "")
document.getElementById("space").setAttribute("onclick", "")
document.getElementById("space").style.backgroundColor="green"
document.getElementById("blank" + l).style.margin = "5px 50px"
}else{
console.log("correct")
document.getElementById("blank" + l).innerHTML = clickon + " "
document.getElementById(clickon).setAttribute("onmouseover", "")
document.getElementById(clickon).setAttribute("onmouseout", "")
document.getElementById(clickon).setAttribute("onclick", "")
document.getElementById(clickon).style.backgroundColor="green"
}
}else if(clickon != letter[l]){
wrong = wrongcheck++
}
}
console.log("_____")
}
if you want I can send you the entire thing.
I tried to create a Html / Js money counter but if i update, it updates one tick and then it resets itself to an old value. I tried creating a function named update and let it run every time the money value changes, but that did not work either.
<html>
<head>
<title>Betting Simulator Test!</title>
</head>
<body>
<br/>
<p id="p1">You have 500$</p>
<br/>
<form name="CoinFlip" action="" onsubmit="Create()" method="post">
Coins: <input type="text" name="Csubmit">
<input type="submit" value="Flip the Coin">
</form>
<script type="text/javascript">
Balance = 500;
function Game() {
if(Balance >= 1) {
var Coin = confirm("You have put " + sub + "$ in the CoinFlip!");
if(Coin == true) {
var flip = true
if(flip == true) {
alert("You won " + sub + "$");
Balance = Balance + sub*2 - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
} else {
alert("You lost " + sub + "$");
Balance = Balance - sub;
Update = document.getElementById("p1").textContent="You have " + Balance + "$";
}
} else {
}
} else {
alert("You ran out of Money");
}
}
function Create() {
sub = document.forms["CoinFlip"]["Csubmit"].value;
if(sub <= Balance && sub > 0) {
Game();
} else {
alert("value does not make any sense!");
}
}
</script>
</body>
You have multiple problems. The first one is that you submit a form each time you play, so the page refreshes, and everything is lost. You could find a workaround to avoid this (see this), but in this case, a form is really not needed.
Also, the user is always going to win because you always set flip to true. You can simulate a random win by using this snippet:
var win = Math.round( Math.random() ); // 1 or 0 (truthy or falsy)
Here is a working example:
var balance = 500;
document.getElementById('flip').addEventListener('click', play);
function play(){
// parseInt() converts a String to an integer (10 is for decimal base)
var bet = parseInt(document.getElementById('bet').value, 10);
if(bet <= balance && bet > 0)
{
var accepted = confirm("Do you really want to bet " + bet + "$?");
if(accepted)
{
var win = Math.round( Math.random() ); // Random win
if(win)
{
alert("You won " + bet + "$!");
balance += bet;
}
else
{
alert("You lost " + bet + "$...");
balance -= bet;
}
if(!balance){ alert('You ran out of money...'); }
document.getElementById('p1').textContent = "You have " + balance + "$";
}
document.getElementById('bet').value = 0;
}
else
{
alert("Your bet makes no sense!");
}
}
<p id="p1">You have 500$</p>
<p>Coins: <input type="number" value="0" id="bet"> <button id="flip">Flip the coin</button>
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.
I'm populating form fields and prompting the user through them using a javascript recursive loop.
I'm having a problem with the recursion not working as expected.
I have a recursive loop that prompts a user through 6 input fields.
field1 and field2 populate as expected, but field3 and field4 fire off together and field5 and field6 fire off together.
I think it has something to do with global vs. local variables or possibly scoping inside the loop() function, but I'm struggling with figuring it out.
JSFiddle: http://jsfiddle.net/9QtDw/5/
Click on the "Save Data" button to fire off the loop and you can see the loop() function iterate with confirm popups guiding the user.
Any help pointing me in the right direction is greatly appreciated.
var x = 0;
var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]
function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in the fieldnames array
return;
}
confirm( 'Highlight the ' + fieldnames[i] + ' text' );
console.log("outside on click function i=" + i);
//function to be called when button is clicked
$("#text-submit").on("click", function(){
//fieldinfo = $("#cs-ResultText").text();
$('#' + fieldnames[i] + '').val('this is where i = ' + i);
// increment i and recall the loop function for the next field
if(i >= fieldnames.length - 1 ){ return false; }
i=i+1;
console.log(i);
console.log("inside on click function i=" + i);
return loop(i); // the recusive call back into the loop
});
return false;
}
// only fire off the loop call on the first run through, after that it's called on #text-submit click
if( x === 0 ){
loop(x);
}
try this instead:
var x = 0;
var fieldnames = ["field1", "field2", "field3", "field4", "field5", "field6"]
function loop(y) {
i = y;
if (i >= fieldnames.length) { return; }
confirm( 'Highlight the ' + fieldnames[i] + ' text' );
$('#' + fieldnames[i] + '').val('this is where i = ' + i);
return false;
}
$("#text-submit").on("click", function(e){
e.preventDefault();
if(i >= fieldnames.length - 1 ){ return false; }
i=i+1;
loop(i);
});
if( x === 0 ){
loop(x);
}
working fiddle here: http://jsfiddle.net/9QtDw/6/
I hope it helps.
You are not looping!!!
ya just loop for 2 time
you should change your loop function like this:
function loop(y) {
i = y;
if (i >= fieldnames.length) { // check to see if loop has run through the number of elements in the fieldnames array
return;
else
$("#text-submit").trigger('click')
}
I want to produce a validation message in an alert for when any text input within a question is empty. So for example if I have 2 blank text inputs for question 1, if both text inputs are blank, it displays the validation message You have not entered in a value in all the Indivdiaul Marks textbox.
But the problem is that for question 1 for example, if 1 text input is blank but the other is not blank, it does not display the validation message, even though it should do as not all text inputs have been filled for question 1.
My question is that how can I get the validation message to appear if there is any blank text input per question?
Here is a fiddle so you can test it: http://jsfiddle.net/cbyJD/87/
Below is the validation() function code:
function validation() {
// only keeping track of the final message
var alertValidation = "",
// toggle for showing only one error
showOnlyOneError = true;
$("input[data-type='qmark']").each(function(i) {
var questions = $(this).attr("data-qnum");
var marks = parseInt($("[class*=q" + (i+1) + "_ans_text]").text());
var txtinput = $(this).val();
// the message for this question
var msg = '';
if (txtinput == '') {
msg += "\n\u2022 You have not entered in a value in all the Indivdiaul Marks textbox \n";
}
if (marks < 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Need To Remove " + Math.abs(marks) + " Marks";
} else if (marks > 0) {
msg += "\n\u2022 Your Total Marks Remaining does not equal 0 \n - You Have " + marks + " Marks Remaining";
}
// if there is an error for the question, add it to the main message
if (msg.length) {
alertValidation += alertValidation.length ? '\n\n' : '';
alertValidation += "You have errors on Question Number: " + questions + "\n";
alertValidation += msg;
// stop if we only care about the first error
return !showOnlyOneError;
}
});
// show the error messages
if (alertValidation != "") {
alert(alertValidation);
return false;
}
return true;
}
First, add a hidden variable num_groups with the total number of groups.
<p>
<input type='hidden' id='num_groups' name='num_groups' value='2'>
<input id="submitBtn" name="submitMarks" type="submit" value="Submit Marks" />
</p>
Second, change the validate function to work on a single group of questions:
function validation(group) {
var msg = [];
var nb = 0; // Number of blank values
$("input[data-qnum='" + group + "']").each(function() {
if ($(this).val() == '') {
nb++;
return false;
}
});
if (nb != 0) {
msg.push("\u2022 You have not entered in a value in all the Individual Marks textbox");
}
var marks = parseInt($("[class*=q" + group + "_ans_text]").text());
if (marks != 0) {
msg.push("\u2022 Your Total Marks Remaining does not equal 0");
if (marks < 0) {
msg.push("- You Need To Remove " + -marks + " Marks");
} else if (marks > 0) {
msg.push("- You Have " + marks + " Marks Remaining");
}
}
if (msg.length > 0) {
alert("You have errors on Question Number: " + group + "\n\n" + msg.join("\n"));
return false;
} else {
return true;
}
}
Third, change the myClickhandler function to validate all the groups:
myClickHandler = function(e) {
var ng = $('#num_groups').val();
for (var group = 1; group <= ng; group++) {
if (!validation(group)) return false;
}
if (confirm("Are you sure you want to Proceed?")) {
$.ajax({
url: "insertmarks.php",
data: $("#markstbl").serialize(),
async: false,
type: "POST"
});
return true;
} else {
return false;
}
}
JsFiddle here.
The validation() function returns true no matter what it finds.
You need to declare a variable at the top of this function called errors or similar, with a value of false. For everywhere in the function that an error is found, set the value of errors to true.
At the close of the function with...
return !errors; // return the value of errors NOT'ed
Then you call call validation() in a test, like so...
if (validation()) {
// everything is groovy
} else {
// make them do the form over, or something
}