Javascript code and methods do not work - javascript

I recently started learning javascrpt, but I have some experience with C#. My school gave me an old text book called Complete Concepts and Techniques(second Edition). this book was written by Shelly Cashman and Dorin Quasney... My problem is that I cant get any of the methods or functions to work. Here are 2 of my most current issues:
var scrollMsg = "Mortage rates are at their lowest!"
var msgSpace = "--- ---"
var beginPos = 0
function scrollingMsg() {
document.msgForm.scrollingMsg.value =
scrollMsg.substring(beginPos,scrollMsg.length)+msgSpace+scrollMsg.substring(0,begi
nPos)
beginPos = beginPos + 1
If (beginPos > scrollMsg.length) {
beginPos = 0
}
window.setTimeout("scrollingMsg()",200)
}
function doMort() {
document.MortCalc.Amount.value=" "
document.MortCalc.Rate.value=" "
document.MortCalc.Years.value=" "
document.MortCalc.Payment.value" "
document.MortCalc.Amount.focus()
}
The scrollingMsg() function does not work. It does not place anything in the scrollingMsg text box. So there is no message in it. My second issue is with the doMort() function. The function does clear any of the boxes nor does it set a focus. Can you please tell me what's wrong. P.S. These are not my own code. These were project codes from the txt book, but they do not work.

Try adding semicolons after each statement, and you have a typo ('If' needs to be lowercase).

I fixed the code to comply with JSLint, use this site to verify your javascript
http://www.javascriptlint.com/online_lint.php
var scrollMsg = "Mortage rates are at their lowest!";
var msgSpace = "--- ---";
var beginPos = 0;
function scrollingMsg() {
document.msgForm.scrollingMsg.value = scrollMsg.substring(beginPos,scrollMsg.length) + msgSpace + scrollMsg.substring(0,beginPos);
beginPos = beginPos + 1;
if (beginPos > scrollMsg.length) {
beginPos = 0;
}
window.setTimeout("scrollingMsg()",200);
}
function doMort() {
document.MortCalc.Amount.value=" ";
document.MortCalc.Rate.value=" ";
document.MortCalc.Years.value=" ";
document.MortCalc.Payment.value=" ";
document.MortCalc.Amount.focus();
}

Related

Print Incremental List items Javascript

This is a pure JavaScript question no jQuery please.
Trying to make a JavaScript Dartboard score keeper. Running into an issue of printing an incremental list. When you click a part of the dartboard would like to calculate throws 1, 2, and 3. The problem is I would like to print off those throws in incremental list format.
HTML:
<button class="score-section" data-value="20" data-multiplier="1">20</button>
<ul id="dartTotals">
<li>Throw 1: {total}</li>
<li>Throw 2: {total}</li>
<li>Throw 3: {total}</li>
</ul>
JavaScript
document.body.onclick = function(e){
e = e.target;
if (e.className && e.className.indexOf('score-section') != -1) {
var i = 0;
(function increment(){
document.getElementById('dartTotals').innerHTML += "<li> Throw " + ++i + ": " + " total </li>";
}());
}
}
The only thing I've been able to do is add 1 to i and just keep printing that off with out incrementing i. Or run a for loop and print off the list but it does it 3 at a time. Could someone assist in helping to show how I can go about making this incremental list with each click? Thanks in advance.
JSFIDDLE
Update:
Updated Fiddle
On body click the function was getting reset. Moved var i, now called dartThrow out of the function scope and is working as expected.
var dartThrow = 0;
document.body.onclick = function(e) {
e = e.target;
if (e.className && e.className.indexOf('score-section') != -1) {
(function increment() {
document.getElementById('dartTotals').innerHTML += "<li> Throw " + ++dartThrow + ": " + " total </li>";
}());
}
}
You're setting $i to 0 on every click and then increment that value. Just do a variable outside your functions scope and then it should increment properly everytime with the code you already do have. You'll just need a reset when $i reaches your total throw count that you want.

Accept user input and multiply by 0.00000116414, copy results to clipboard

This code pops up asking for the users input, and multiplies it by 0.00000116414.
I want to change this into a text input field and calc button, then perhaps add the ability to copy to the clipboard. How might I do this?
<html>
<head>
<meta name="Recommended Share Difficulty Calculator" content="[Share Dicciculty Calculator]" />
<title>Recommended Share Difficulty</title>
<script type="text/javascript">
function MathThing()
{
input = prompt("Enter your max KH/s.", "");
if (input==null || input=="")
{
return false;
}
share = 0.00000116414 ;
total = input * share;
alert(input + " * " + share + " = " + total);
}
</script>
</head>
<body>
Calculate
</body>
</html>
In order to manipulate the contents of a users clipboard you will need to utilize Flash. There is a great helper library called ZeroClipboard. I've set up a basic demo (that uses your JavaScript) that uses this JavaScript:
var client = new ZeroClipboard(
$("#copy"), {
moviePath: "http://zeroclipboard.org/javascripts/zc/ZeroClipboard_1.3.2.swf"
});
client.on('dataRequested', function (client, args) {
client.setText((function () {
input = prompt("Enter your max KH/s.", "");
if (input == null || input == "") {
return;
}
share = 0.00000116414;
total = input * share;
alert('"'+input + " * " + share + " = " + total+'" copied to your clipboard');
return input + " * " + share + " = " + total;
})());
});
This code follows the examples provided in the Zero Clipboard, the odd thing is it doesn't seem to work 100% of the time. I do most of my work on computers that don't have Flash so I don't know if this reliability is part of the library or my computer. Good luck.
Copying cross-browser is tricky.
Here is some super-simple code showing an input + button use case:
var el = document.getElementById('input-id');
var sub = document.getElementById('submit-id');
var calc = function(e){
var q = el.value;
var share = 0.00000116414;
if (q.length > 0){
var res = q * share;
alert(res);
}
};
sub.addEventListener('click', calc);
Fiddle: http://jsfiddle.net/G6T76/3/
You'll probably want to do a bit more validation on the input, though.

Change form input value with javascript

I am trying to change the input value of a hidden form to update the score of a game in my database.
I have this form code on a php page that displays and plays the game.
<form id ="recordForm" method="POST" action="updatePHP.php">
<input type='hidden' name="record" id='record' value='' />
</form>
And am trying to change the value of the hidden input field with this javascript. This is in the separate javascript file that is controlling the game.
function postPHP(newRecord){
alert("POST TO PHP"); //test to make sure I am calling this function
alert (newRecord); //alerts the correct value
var elem = document.getElementById('record');
elem.value = 12;
// document.getElementById('record').value = newRecord;
// document.getElementById('recordForm').submit();
};
There are a lot of topics on this subject but I am just not able to figure out what I am doing wrong. Any suggestions?
you should try
elem.value = newRecord;
Your JS function should work like this, i tested, more less what you already have. I remove the alerts since you don't need them anymore and leave what you have commented. This means your JS function isn't the problem.
function postPHP(newRecord)
{
document.getElementById('record').value = newRecord;
document.getElementById('recordForm').submit();
};
Don't forget to sent the parameter when calling the JS function, i did it with a button
<button onClick="postPHP('14')">Change</button>
since your JS function is in a separate file don't forget to include it in the File where you call the function
<head>
<script type="text/javascript" src="PATH/exampleName.js"></script>
</head>
Replace the src of the above tag to your needs
And last but not least check your updatePHP.php with a call to the method print_r
print_r($_POST);
All that should make the trick
Thank you for all your suggestions! This was my first question ever, I will look at all of them and see if I can get it working.
This is where I am calling postPHP:
function checkScore(score, record) {
alert('Score= ' + score);
alert ('Record= '+ record);
if(score < record || record === 0){
alert ("NEW RECORD"); //this alert is displayed when needed
postPHP(score);
}
};
and checkScore was called when the user moved a target crate back to the beginning spot and the following statement was executed
if (this.hasWon()) {
var finalScore = this.getScore();
var record = this.getRecord();
checkScore(finalScore, record);
return ret; //moving not allowed
}
there are some access methods used there.
//access methods
Board.prototype.hasWon = function() {
return state === 1;
};
Board.prototype.getScore = function() {
return score;
};
Board.prototype.getWt = function(r, c) {
return b[r][c];
};
Board.prototype.getData = function() {
return {"bobR": bobR, "bobC": bobC, "bobDir": bobDir,
"tgtR": tgtR, "tgtC": tgtC,
"startC": startC, "n": n};
};
Board.prototype.getRecord = function(){
var s = "" + window.location;
var ampIdx = "" + s.indexOf("&");
ampIdx = parseInt(ampIdx);
ampIdx = ampIdx + 7;
var record = "" + s.substring(ampIdx);
//alert("Puzzle Record= " + record);
record = parseInt(record);
return record;
}
;
I do have the javascript included. I do call it once in the body of the HTML, for some reason it doesn't display the game correctly when included in the head.
Again, thank you for the help! I will let you know what I get to work!
This is what I got to work.
function postPHP(newRecord, seed) {
alert("POST TO PHP");
var inner = "<input type='hidden' name='record' id='record' value=" + newRecord + " >"+
"<input type='hidden' name='seed' id='seed' value=" + seed + " >";
document.getElementById('recordForm').innerHTML = inner;
document.getElementById('recordForm').submit();
};
Thanks again for all the help, I just don't know why the first method wasn't working. This is my first attempts at PHP and javascript.

Javascript functions. variable result. why undefined or doesn't if else statement function?

I need the values of the name, address, size, and topping fields to appear in a text box. Without problems the name and address appears correctly. However I can't seen to get the size function to work. It is a radio button, and thus I need only one size to appear. I haven't even tried an if else for the checkbox yet. Here is my code
<html>
<head>
<script>
function pizza() {
document.pizzaboy.comments.value = "Name:" + " " + pizzaboy.name.value + "\n" + "Address:" + " " + pizzaboy.address.value + "\n" + document.getElementById("small").value + document.getElementById("medium").value + document.getElementById("large").value + "\n" + pizzaboy.toppings.value;
{
var rslt = "";
if (document.pizzaboy.size[0].checked) {
rslt = rslt + "Size=Small\n";
} else if (document.pizzaboy.size[1].checked) {
rslt = rslt + "Size=Medium\n";
} else rslt = rslt + "Size=Large\n";
return rslt;
}
}
</head>
The second Javascript bracket might be throwing you an error, keeping your code from running correctly.
In this post, several (more general) ways to get values of radio buttons are explained:
Checking Value of Radio Button Group via JavaScript?
The first answer is using jQuery, but the following answers will help you i think.
You should try this. Answer here if you need further assistance.

How do I make a loop advance using onclick?

I've been trying to figure this out for a while, and I'm totally stumped.
I'm writing a program that is supposed to display a basic series of multiple-choice questions. You see a question, you click one of the answers, and you move on to the next question.
The problem is, I can't figure out how to display one question, then display the next question when the user clicks one of the buttons. Nothing happens when I click a button. What's going wrong?
// progress meter
var progress = new Array();
for (var i = 0; i < questions.length; i++) progress.push("0");
var i = 0;
display(0);
// display questions
function display(i) {
var prg_string;
for (var j = 0; j < progress.length; j++) prg_string += progress[j];
document.write(
"<div id = 'background'>"
+ "<div id = 'progress'>" + progress + "</div>"
+ "<div id = 'title'>-JogNog Test v1-<br></br>" + tower + "</div>"
+ "<div id = 'question'>" + questions[i].text + "</div>"
+ "<div id = 'stats'>Level " + level + "/" + total_levels + " Question " + (i + 1) + "/" + questions.length + "</div>"
+ "</div>"
);
document.write("<button id = 'answer1' onclick = 'next(questions[i].answers[0].correct)'>" + questions[i].answers[0].text + "</button>");
if (questions[i].answers.length > 0)
document.write("<button id = 'answer2' onclick = 'next(questions[i].answers[1].correct)'>" + questions[i].answers[1].text + "</button>");
if (questions[i].answers.length > 1)
document.write("<button id = 'answer3' onclick = 'next(questions[i].answers[2].correct)'>" + questions[i].answers[2].text + "</button>");
if (questions[i].answers.length > 2)
document.write("<button id = 'answer4' onclick = 'next(questions[i].answers[3].correct)'>" + questions[i].answers[3].text + "</button>");
}
// go to next question, marking whether answer was right or wrong
function next(correct) {
if(correct) progress[i] = "T";
else progress[i] = "F";
i += 1;
display(i);
}
I haven't read through your code, (you might want to work on posting SSCCEs by focusing just on the part that handles the loop) but I get the feeling a loop is not what you want here. Loops are great if you need to automatically iterate through something. But really, you want to display only a single question at a time.
The easiest way to do this, assuming you have a means of handling each question independently, is just to keep track of which question the user is up to. Display that question. When the user submits an answer, call whatever function renders a question using the counter, plus one. Make sure to check that you haven't hit the end of the quiz so that you don't reference a question that doesn't exist.
Here's some pseudocode:
var questionNumber, questions; //assume these already have values
function printQuestion(questionNumber){ ... }
function nextQuestion(){
if(questionNumber < questions){
questionNumber++;
printQuestion(questionNumber);
}
else{
showResults();
}
}
I agree with #ngmiceli that a loop isn't what you want here. You want to display one question, and then create click event handlers that will move on to the next question when the user selects an answer to the previous question.
I went ahead and created a different setup to demonstrate. You can see a demo here:
-- jsFiddle DEMO --
But I'll walk through the process. First, I set up a basic HTML document:
<body>
<h1>-Test v1-</h1>
<h2>Simple Math</h2>
<div id="container">
<div><span id="numRight">0</span> of <span id="numQuestions">0</span></div>
<div id="question"></div>
<div id="answers"></div>
</div>
</body>
Then, I created a questions array, each element in the array being an object. Each question object contains the question itself, an array of possible answers, and an "answerIdx" property that indicates the array index of the correct answer.
questions = [
{
question: 'What is 0 / 6 ?',
options: ['0','1','2'],
answerIdx: 0
},
{
question: 'What is 2 + 2 ?',
options: ['72','4','3.5'],
answerIdx: 1
}
]
I also created some other variables that point to the HTML elements I am going to want to manipulate:
numRight = 0,
numQuestions = 0,
answerDiv = document.getElementById('answers'),
questionDiv = document.getElementById('question'),
numRightSpan = document.getElementById('numRight'),
numQuestionsSpan = document.getElementById('numQuestions');
Next, I created a 'displayQuestion' function which takes a single question object as a parameter:
function displayQuestion(q) {
// insert the question text into the appropriate HTML element
questionDiv.innerHTML = q.question;
// remove any pre-existing answer buttons
answerDiv.innerHTML = '';
// for each option in the 'options' array, create a button
// attach an 'onclick' event handler that will update
// the question counts and display the next question in the array
for(i = 0; i < q.options.length; i++) {
btn = document.createElement('button');
btn.innerHTML = q.options[i];
btn.setAttribute('id',i);
// event handler for each answer button
btn.onclick = function() {
var id = parseInt(this.getAttribute('id'),10);
numQuestionsSpan.innerHTML = ++numQuestions;
// if this is the right answer, increment numRight
if(id === q.answerIdx) {
numRightSpan.innerHTML = ++numRight;
}
// if there is another question to be asked, run the function again
// otherwise, complete the test however you see fit
if(questions.length) {
displayQuestion(questions.shift());
} else {
alert('Done! You got '+numRight+' of '+numQuestions+' right!');
}
}
answerDiv.appendChild(btn);
}
}
Finally, I displayed the first question:
displayQuestion(questions.shift());

Categories

Resources