I have an script for producing random quotes using an onClick. However, what I need is for a specific quote to open as the default. After that, onClicks should produce random results. Here's what I've got so far:
<button onClick="quotes()">ASK then CLICK</button>
<br>
<textarea id="txtbox" style="width:170px; readonly></textarea>
<br>
<br>
<script>
function quotes() {
var aquote = new Array;
aquote[0] = " This SHOULD ALWAYS APPEAR FIRST ";
aquote[1] = "Think twice about this ";
aquote[2] = "Save your money.... ";
aquote[3] = "Real Estate is good ";
aquote[4] = "Visit the Islands "
rdmQuote = Math.floor(Math.random() * aquote.length);
document.getElementById("txtbox ").value = aquote[rdmQuote];
}
window.onload = quotes;
</script>
You can reorganise your code like this and create dedicated functions for either a random quote or a fixed one:
<button onClick="randomQuote()">ASK then CLICK</button>
...
<script>
var quotes = [
" This SHOULD ALWAYS APPEAR FIRST ",
"Think twice about this ",
"Save your money.... ",
"Real Estate is good ";
"Visit the Islands "
];
function randomQuote()
{
showQuote(Math.floor(Math.random() * quotes.length));
}
function showQuote(index) {
document.getElementById("txtbox ").value = quotes[index];
}
window.onload = function() {
showQuote(0);
};
</script>
You could display the default text in your HTML itself, and then change the textarea's value with a random quote.
HTML
<textarea id="txtbox">This SHOULD ALWAYS APPEAR FIRST</textarea>
JS
var aquote = [
"Think twice about this ",
"Save your money.... ",
"Real Estate is good ",
"Visit the Islands "
];
var random = -1;
function quotes() {
var temp = random;
// Make sure we do not display the same quote twice in a row
while(temp == random) temp = Math.floor(Math.random() * aquote.length);
random = temp;
document.getElementById("txtbox").innerHTML = aquote[random];
}
JS Fiddle Demo
your only problem is syntax errors. You have an extra space in getElementById("txtbox ") and a missing quote in the style declaration for textarea, otherwise code works using :
document.getElementById("txtbox").value = aquote[rdmQuote];
http://jsfiddle.net/CkaMW/
Related
I've made a JS/HTML quiz, and I want all the words entered in the text fields to be displayed at the bottom of the page on submission.
The error is in the showResults function, which isn't working the way I intend it to. I'm a beginner at using the querySelector but what I want to do is use the variable answerContainers to store only the .answers part of quizContainer, and then the toSearch variable to store only the values of submitted answers from answerContainers. Finally, I want to print the contents of toSearch to the screen in string form.
Here's my code:
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
var myQuestions = ["1. What is your dream destination?",
"2. If you could have one wish right now, what would it be?",
"3. What are your career goals?",
"4. Name an artist whose music you enjoy.",
"5. What are your hobbies?",
"6. Name a few public figures you admire.",
"7. Who is your favourite actor?",
"8. Which family member do you love the most?",
"9. If you could have any animal as your pet, what would it be?",
"10. Name a movie you’ve been planning to watch but haven’t yet had the time.",
"11. What kind of weather do you like the most?",
"12. Name a book or movie that you’ve always loved."];
function showQuestions(myQuestions, quizContainer){
var output = [];
for(var j = 0; j <= 11; j++)
{
var answer = '<label>'
+ '<input type="text" name=""+j+"" id=""+j+"">'
+ '</label>';
output.push(
'<div class="question">' + myQuestions[j] +'</div>'
+ '<div class="answers">' + answer + '</div>'
);
}
quizContainer.innerHTML = output.join("");
}
function showResults(questions, quizContainer, resultsContainer){
var answerContainers = quizContainer.querySelectorAll('.answers');
var toSearch = [];
for(var i=0; i <= 11; i++){
toSearch.push(answerContainers[i].querySelector('input[name=""+i+""]')).value;
}
resultsContainer.innerHTML = toSearch.toString();
}
<!DOCTYPE html>
<html>
<head>
<h2>Interests Questionnaire</h2>
<h4>Answer in 1-5 words each.</h4>
<br>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div id="quiz"></div>
<div id="results"></div>
<script src = "test.js"></script>
<script> showQuestions(myQuestions, quizContainer); </script>
<input type="button" value = "Submit" id = "submit" onclick = "showResults(myQuestions, quizContainer, resultsContainer)">
</body>
</html>
In its current form, the code gives the error "JavaScript error: TypeError: quizContainer is null on line 52". What am I doing wrong and how can I fix it?
There were a few errors in your code - a misplaced parens, that sort of thing. I found/fixed the ones that were preventing success and got the answers to display in a string. You should be able to take it from here.
List of errors:
(1) toSearch.append() is not correct - use toSearch.push()
(2) You cannot have name or id attributes that begin with a number.
(3) This line was incorrect in a few places:
toSearch.append(answerContainers[i].querySelector('input[name=""+i+""]')).value;
should be:
toSearch.push(answerContainers[i].querySelector('input[name="a'+i+'"]').value);
var quizContainer = document.getElementById('quiz');
var resultsContainer = document.getElementById('results');
var submitButton = document.getElementById('submit');
var myQuestions = ["1. What is your dream destination?",
"2. If you could have one wish right now, what would it be?",
"12. Name a book or movie that you’ve always loved."];
function showQuestions(myQuestions, quizContainer){
var output = [];
for(let j=0; j <= myQuestions.length-1; j++){
var answer = `
<label>
<input type="text" name="a${j}" id="a${j}">
</label>`;
output.push(
`<div class="question">${myQuestions[j]}</div>
<div class="answers">${answer}</div>`
);
}
quizContainer.innerHTML = output.join("");
}
function showResults(myQuestions, quizContainer, resultsContainer){
var answerContainers = quizContainer.querySelectorAll('.answers');
// console.log(answerContainers);
var toSearch = [];
for(var i=0; i <= myQuestions.length-1; i++){
//console.log(answerContainers[i].querySelector('input[name="a'+i+'"]').value);
toSearch.push(answerContainers[i].querySelector('input[name="a'+i+'"]').value);
var x = 0;
}
resultsContainer.innerHTML = JSON.stringify(toSearch);
//userAnswer = (answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
}
showQuestions(myQuestions, quizContainer);
<h2>Interests Questionnaire</h2>
<h4>Answer in 1-5 words each.</h4>
<br>
<div id="quiz"></div>
<div id="results"></div>
<input type="button" value = "Submit" id = "submit" onclick = "showResults(myQuestions, quizContainer, resultsContainer)">
There are a few problems here:
You have h2, br tags in the <head> of your page. Don't do that. Those kind of tags belong in the <body> tag of the page.
That error is telling you that quizContainer is null - if you look at the line of your code that is declaring quiz container, it is attempting to grab an element by ID - specifically 'quiz'. It can't find it. Possibly because you don't have a <body> tag.
Also - in your showResults function, you have a loop. Outside of that loop, is this line:
userAnswer =(answerContainers[i].querySelector('input[name=question'+i+']:checked')||{}).value;
You are trying to access the answerContainers array with the variable i outside of the loop where i is defined.
So I am attempting to display all the questions and responses from my Firebase database. It is showing up fine, but it looks ugly, because there is no space between the question and responses. I've tried using the createElement feature as well as .innerHTML to add a nonbreaking space. Nothing is working. Here is the code I have thus far: Thanks for your help!
<button id="all" onclick="button()"> View All </button>
<h4> All Users: </h4>
<script>
function button(){
var userRef = new Firebase("https://speedpoll-1fd08.firebaseio.com");
userRef.on("value", function(snapshot) {
// The callback function will get called twice, once for "fred" and once for "barney"
snapshot.forEach(function(childSnapshot) {
// key will be "fred" the first time and "barney" the second time
var key = console.log(childSnapshot.key());
// childData will be the actual contents of the child
// var userInfo = console.log(childSnapshot.val());
var element = document.getElementById("viewAll");
var para = document.createElement("h5");
var node = document.createTextNode("Question: " + childSnapshot.key());
console.log(childSnapshot.child("Option1").child('Response1').val());
var node1= document.createTextNode("Response 1: " + childSnapshot.child("Option1").child('Response1').val());
//var space = document.createElement(" ");
element.innerHTML += " ";
var node2= document.createTextNode("Response 2: " + childSnapshot.child('Option2').child('Response2').val());
var node3= document.createTextNode("Response 3: " + childSnapshot.child('Option3').child('Response3').val());
para.appendChild(node);
//para.appendChild(space);
para.appendChild(node1);
para.appendChild(node2);
para.appendChild(node3);
element.appendChild(para);
});
});
}
</script>
<div id="viewAll">
</div>
You can add a line by adding an <hr> element, as explained here: http://www.htmlgoodies.com/tutorials/getting_started/article.php/3479441
Like this one:
You can also add <div> sections for each element, and style the margins, paddings and borders with CSS. The same for <p> sections.
You can play around with this JSFiddle:
http://jsfiddle.net/jmgomez/n0e1ev8e/
Check this out also on how to style borders with CSS: http://www.w3schools.com/css/css_border.asp
<html>
<script type="text/javascript">
var map = null;
jQuery(function($) {
L.marker([50.065407, 19.945104], {title: 'Cat'})
.bindPopup('<h3>Cat</h3><p><strong>color</strong>black<br><strong>Dog</strong>white</p>')
.addTo(map);
</script>
</html>
I need to get values from <h3> and <strong>.
script = doc.select("script");
but how to get: "Cat color black"
"Dog white" ?
p = Pattern.compile("^[a-z]+"); m = p.matcher(doc.html()); return String.valueOf(m); it returns me java.util.regex.Matcher#4167d5f8
Do like this:
String content = //text you posted above
Pattern p = Pattern.compile(".bindPopup\\('(.*)'\\)");
Matcher m = p.matcher(content);
while (m.find()) {
String text = m.group(1);
String htmlStripped = text.replaceAll("<[^>]*>", " ");
System.out.println(htmlStripped);
}
Ok, in essence I want to create a short quiz that has a next and previous button. I want to loop through two arrays, questions and choices, and have a score at the end. I have read chapters on the DOM and Events and it is just not clicking apparently.
Really I need a little bit of code that shows a concrete example of how to manipulate the DOM. What I have so far are only the arrays, and a function declaring that x is in fact getting my element by id. haha.
Sorry I don't have more code to give. I tried to attach the id to a paragraph, and then get it by it's id and document.write the array, but that replaces the button. If you run the code below you'll see what I'm saying.
<!DOCTYPE html>
<html>
<head>
<title>Bom</title>
</head>
<body>
<input type="button" value="Iterate" id="myButton" onclick="iter_onclick()">
<p id="qArray">Some Text</p>
<script>
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","","The Smurf Girl"]];
function iter_onclick () {
var x = document.getElementById("qArray");
document.write("Hello World");
}
</script>
</body>
</html>`
Like I said, this is my first attempt at truly manipulating the DOM, and I know what I want to do. I just don't know how to do it. I am understanding all the syntax and events and objects and such. But, I'm not really sure how to apply it. Also, no Jquery. I want to know how to create applications with Javascript and then work my way into Jquery. Thanks people.
This will loop through your questions, hope this helps you to proceed.
var qArray = ["Who is my dog?",
"who is the prez?",
"Who is my girlfriend?",
"Who am I?"];
var cArray = [
["Bill", "Billy", "Arnold", "Tyler"],
["Oz", " Buffon", "Tupac", "Amy"],
["Tony Blair", "Brack Osama", "Barack Obama", "Little Arlo"],
["Emma Stone", "Tony the Tiger", "Amy Dahlquist", "The Smurf Girl"]
];
var index = 0;
function iter_onclick() {
//if this is the last question hide and displays quiz ends
if (index >= qArray.length) {
document.getElementById('qArray').innerHTML = '<div>Quiz End, Thank you</div>'
document.getElementById('myButton').style.visibility = 'hidden ';
return false;
}
var html = ' <div> ' + qArray[index] + ' </div> <div>';
for (var i = 0; i < cArray[index].length; i++) {
html += '<label><input type="radio" name="ans" value="'
+ cArray[index][i] + '"/ > ' + cArray[index][i] + ' </label>';
}
html += '</div > ';
document.getElementById('qArray').innerHTML = html;
index++;
}
Here's a very basic example you can work from. This modifies the existing DOM items. You cannot use document.write() on a document that is already loaded or it will clear everything you have and start over and it's not the most efficient way to put content into the DOM.
This example has a number of fields on the page, it loads a question and then checks the answer when you press the next button.
HTML:
<div id="question"></div>
<input id="answer" type="text"><br><br>
<button id="next">Next</button> <br><br><br>
Number Correct So Far: <span id="numCorrect">0</span>
Javascript (in script tag):
var qArray = ["Who is my dog?", "who is the prez?", "Who is my girlfriend?", "Who am I?"];
var cArray = [["Bill","Billy", "Arnold", "Tyler"],["Oz"," Buffon","Tupac","Amy"],["Tony Blair","Brack Osama","Barack Obama","Little Arlo"],["Emma Stone","Tony the Tiger","Amy Dahlquist","The Smurf Girl"]];
var questionNum = -1;
var numCorrect = 0;
function loadQuestion() {
++questionNum;
if (questionNum >= qArray.length) {
alert("all questions are done");
} else {
document.getElementById("question").innerHTML = qArray[questionNum];
document.getElementById("answer").value = "";
}
}
loadQuestion();
function checkAnswer() {
var answer = document.getElementById("answer").value.toLowerCase();
var allowedAnswers = cArray[questionNum];
for (var i = 0; i < allowedAnswers.length; i++) {
if (allowedAnswers[i].toLowerCase() == answer) {
return true;
}
}
return false;
}
document.getElementById("next").addEventListener("click", function(e) {
if (checkAnswer()) {
++numCorrect;
document.getElementById("numCorrect").innerHTML = numCorrect;
loadQuestion();
} else {
alert("Answer is not correct");
}
});
Working demo: http://jsfiddle.net/jfriend00/gX2Rm/
$('#pm').val(Math.floor(parseFloat(pm*100/100)));
Full code:
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(Math.floor(parseFloat(pm*100/100)));
$('#gg').val(gg);
}
$('#pm').keyup(updatePay);
$('#gg').keyup(updatePay);
</script>
When I use Math.floor it doesn't allow me to enter a second decimal.
I need my code to be able to allow a second decimal place to be filled in, how can I do this in Javascript?
Try this
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
I think you want to round down and allow 2 decimal places,
so if the number is 3546.699433
parseFloat(pm)*100 = 354669.9433
math.floor(354669.9433) = 354669
354669/100 = 3546.69
<script type="text/javascript">
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = $('#pm').val();
var gg = pm/current_price;
// Set the new input values.
$('#pm').val((Math.floor(parseFloat(pm)*100)/100).toFixed(2));
$('#gg').val(gg);
}
$('#pm').change(updatePay);
$('#gg').chnage(updatePay);
</script>
If you want something that gets updated on keyup, try something along these lines
Javascript:
document.getElementById("num1").onkeyup = function(){
var val = (Math.floor(parseFloat( document.getElementById("num1").value)*100)/100).toFixed(2);
if(isNaN(val)){
document.getElementById("result").innerHTML = "pm will appear here";
}
else if(val){
document.getElementById("result").innerHTML = val;
} else {
document.getElementById("result").innerHTML = "pm will appear here";
}
}
HTML:
<body>
<input type="button" id="myButton" value="click me"/>
<span id="result"></span>
<input type="text" id="num1" value="1.1111"></div>
</body>
It's hard to tell what you're trying to achieve, but at a guess I suspect you want the values displayed in pm and gg to have two digits of fractional precision. If so:
function updatePay() {
// Grab all the value just incase they're needed.
var current_price = <?php echo json_encode($current_price); ?>;
var pm = parseFloat($('#pm').val()); // Parse here
var gg = pm/current_price;
// Set the new input values.
$('#pm').val(pm.toFixed(2)); // Round to two places and turn back into text
$('#gg').val(gg.toFixed(2)); // " " " " " " " " "
}
Side note: You have this set as a keyup handler on the gg element, but you're always overwriting what the gg element has in it, without using the value in gg at all. If I were a user, I'd find that pretty irritating.