I have this page:
var count = 0;
function switchStatement() {
var text;
var answers = document.getElementById("userInput").value;
switch (answers) {
case "":
text = (count > 0) ? "You didn't type anything." : "Please type something down...";
if (count < 1)
count++;
else
count = 0;
break;
default:
text = "Good job!";
}
document.getElementById("feedback").innerHTML = text;
document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>
<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">
<p id="feedback"></p>
When the user doesn't type anything before pressing "enter", (that's case = "";), a message will show up. If he does the same thing again, a different message will show up. If he does it a third time, it will loop back to the first message.
How can I add more messages to avoid having such a small loop? Say, if I wanted to have 5 different messages for when the user doesn't type anything, what should I change in my code?
You could use an array of messages :
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."]
Then use the count variable as the index of this array to show the messages one after other.
NOTE: You must init the count to the default value 0 in case the user typed something so the next empty submit will show the first message in index 0.
var count = 0;
var messages = ["message 1...", "message 2...", "message 3...", "message 4...", "message 5..."];
function switchStatement() {
var text;
var answers = document.getElementById("userInput").value;
switch (answers) {
case "":
text = messages[count];
count = count < messages.length - 1 ? count + 1 : 0;
break;
default:
text = "Good job!";
count = 0;
}
document.getElementById("feedback").innerHTML = text;
document.getElementById("userInput").value = "";
}
<p>Please write something down and press "enter".</p>
<input id="userInput" type="text" onKeyDown="if(event.keyCode==13) switchStatement();">
<p id="feedback"></p>
Related
in my while loop I was hoping it will keep prompting the user for entry unless I break out of the loop. However, once I get into my if block it wont to peform printToScreen(message) function unless I terminate the code.
Not sure what I am doing wrong here. I am expecting it to print message before continuing to prompt.
how can I fix this?
let message;
let search;
function printToScreen(message){
let outputDiv = document.getElementById('output');
outputDiv.innerHTML = message;
}
function promptUser (){
search = prompt("Enter student name");
return search;
}
function searchStudent(){
while(true){
search =promptUser();
for(let i = 0; i<students.length; i++){
if(search.toLowerCase() === students[i].name.toLowerCase())
{
let student = students[i];
message = `<h4>Student: ${student.name}</h4>`;
message += `<p> Track: ${student.track}
<br> Achievements:${student.achievements}
<br> Points: ${student.points}
</p>`;
printToScreen(message);
}
else if( search ===null || search.toLowerCase() === 'quit'){
message = `<p>Thanks.Goodbye! </p>`;
printToScreen(message);
break;
}
else{
message = `<p> Student ${search} does not exist. Try Again!</p>`;
printToScreen(message);
}
}
}
}
searchStudent();
That's because the browser won't redraw the page while it is still computing some js.
What you could do is replace your while(true) by a recursive call in a setTimeout:
function searchStudent(){
search =promptUser();
for(let i = 0; i<students.length; i++){
if(search.toLowerCase() === students[i].name.toLowerCase())
{
let student = students[i];
message = `<h4>Student: ${student.name}</h4>`;
message += `<p> Track: ${student.track}
<br> Achievements:${student.achievements}
<br> Points: ${student.points}
</p>`;
printToScreen(message);
}
else if( search ===null || search.toLowerCase() === 'quit'){
message = `<p>Thanks.Goodbye! </p>`;
printToScreen(message);
break;
}
else{
message = `<p> Student ${search} does not exist. Try Again!</p>`;
printToScreen(message);
}
}
setTimeout(function(){
searchStudent();
},5);
}
searchStudent();
I'm trying to create a simple game where you have to answer the correct answer from a calculation.
I already have the function to generate random calculations, but i don't know how to compare it with the result which the user writted.
I tried to make the if, so when the user press the submit button, then the app will try to determine if that's the correct answer.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var question = document.getElementById("textQuestion");
var answer = document.getElementById("textAnswer");
function rollDice() {
document.form[0].textQuestion.value = numArray[Math.floor(Math.random() * numArray.length)];
}
function equal() {
var dif = document.forms[0].textQuestion.value
if (dif != document.forms[0].textAnswer.value) {
life--;
}
}
<form>
<input type="textview" id="textQuestion">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
</form>
<input type="button" name="start" onclick="">
document.forms[0].textQuestion.value looking for an element with name=textQuestion, which doesn't exist. Use getElementById instead or add name attribute (needed to work with the input value on server-side).
function equal() {
if (document.getElementById('textQuestion').value != document.getElementById('textAnswer').value) {
life--; // life is undefined
}
}
// don't forget to call `equal` and other functions.
This is probably what you're looking for. I simply alert(true || false ) based on match between the random and the user input. Check the Snippet for functionality and comment accordingly.
var numArray = ["10/2", "5x5", "12-22", "5-6", "20-70"];
var questionElement = document.getElementById("textQuestion");
var answerElement = document.getElementById("textAnswer");
function rollDice() {
var question = numArray[Math.floor(Math.random() * numArray.length)];
questionElement.setAttribute("value", question);
}
//rolldice() so that the user can see the question to answer
rollDice();
function equal()
{
var dif = eval(questionElement.value); //get the random equation and evaluate the answer before comparing
var answer = Number(answerElement.value); //get the answer from unser input
var result = false; //set match to false initially
if(dif === answer){
result = true; //if match confirmed return true
}
//alert the match result
alert(result);
}
document.getElementById("start").addEventListener
(
"click",
function()
{
equal();
}
);
<input type="textview" id="textQuestion" value="">
<br>
<textarea id="textAnswer" form="post" placeholder="Answer"></textarea>
<input type="button" id="start" value="Start">
There's more I would fix and add for what you're trying to achieve.
First of you need a QA mechanism to store both the question and the correct answer. An object literal seems perfect for that case: {q: "", a:""}.
You need to store the current dice number, so you can reuse it when needed (see qa_curr variable)
Than you could check the user trimmed answer equals the QA.a
Example:
let life = 10,
qa_curr = 0;
const EL = sel => document.querySelector(sel),
el_question = EL("#question"),
el_answer = EL("#answer"),
el_check = EL("#check"),
el_lives = EL("#lives"),
qa = [{
q: "Calculate 10 / 2", // Question
a: "5", // Answer
}, {
q: "What's the result of 5 x 5",
a: "25"
}, {
q: "5 - 6",
a: "-1"
}, {
q: "Subtract 20 from 70",
a: "-50"
}];
function rollDice() {
qa_curr = ~~(Math.random() * qa.length);
el_question.textContent = qa[qa_curr].q;
el_lives.textContent = life;
}
function checkAnswer() {
const resp = el_answer.value.trim(),
is_equal = qa[qa_curr].a === el_answer.value;
let msg = "";
if (resp === '') return alert('Enter your answer!');
if (is_equal) {
msg += `CORRECT! ${qa[qa_curr].q} equals ${resp}`;
rollDice();
} else {
msg += `NOT CORRECT! ${qa[qa_curr].q} does not equals ${resp}`;
life--;
}
if (life) {
msg += `\nLives: ${life}`
} else {
msg += `\nGAME OVER. No more lifes left!`
}
// Show result msg
el_answer.value = '';
alert(msg);
}
el_check.addEventListener('click', checkAnswer);
// Start game
rollDice();
<span id="question"></span><br>
<input id="answer" placeholder="Your answer">
<input id="check" type="button" value="Check"> (Lives:<span id="lives"></span>)
The above still misses a logic to not repeat questions, at least not insequence :) but hopefully this will give you a good start.
I am new to Javascript and I was making a little chat bot, nothing to fancy, but I am stuck in a problem where if I input something to it that matches a value inside an array it will execute the if and the else condition.
function readInput(){
var words = ["hello", "hi", "holis", "holus"];
var userInput = document.getElementById("userInput").value.toLowerCase();
console.log(" Users says: " + userInput);
for(var i = 0; i < words.length; i++){
if(userInput == words[i]){
console.log("bot says: " + "hi!");
}else {
console.log("bot says " + "i dont understand");
}
}
//clean user input
var clearInput = document.getElementById("userInput").value="";
}
<input type="text" id="userInput" value="">
<button type="button" name="button" onclick="readInput()">Say</button>
Any help will be appreciated
Modify your for statement.
Define a variable to check if your script know the word. In the for statement, if the input word is in the words, then set the variable true then break. Finally if the check variable is false, than say I don't understand:
var check = false
for (var i = 0; i < words.length; i++) {
if (userInput == words[i]) {
console.log("bot says: " + "hi!");
check = true;
break
}
}
if (!check) {
console.log("bot says " + "i dont understand");
}
I have basic form with input text boxes and a checkboxes. The example currently shows two items. I am trying to use a switch case to determine what was checked and then calculate a total based on the quantity and user selection. I am getting an error inside the switch case for mufin1.checked == true. How can get the proper value to be returned? JSFIDDLE
JS
function charge(){
var q_muffin1 = document.getElementById('muffin_quantity1');
var muffin1 = document.getElementById('muffin1');
var q_muffin2 = document.getElementById('muffin_quantity2');
var muffin2 = document.getElementById('muffin2');
var charge;
var form = document.getElementById("muffinOrder");
var checkbox = form.getElementsByTagName("checkbox");
switch (checkbox.checked) {
case (mufin1.checked == true):
charge += q_muffin1 * muffin1;
break;
case (mufin2.checked == true):
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
window.alert("Your total is: $" + charge);
return false;
}
html
<form action="" id="muffinOrder" onsubmit="return charge()">
Quantity: <input type="text" name="muffin_quantity1" id="muffin_quantity1"><input type="checkbox" name="muffin1" id="muffin1" value=".59">Blueberry Muffin .59¢<br />
Quantity: <input type="text" name="muffin_quantity2" id="muffin_quantity2"><input type="checkbox" name="muffin2" id="muffin2" value=".69">Banana Nutted Muffin .90¢<br />
<input type="submit" value="Submit" >
</form>
Assuming you don't want to handle the case where both checkboxes are checked, you could write it like this :
switch (true) {
case (mufin1.checked):
charge += q_muffin1 * muffin1;
break;
case (mufin2.checked):
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
But your whole code would probably be cleaner without those variables xxx1 and xx2. I'm not sure of the whole goal but this could be something like that :
var charge = 0;
[1,2].forEach(function(id){
var muffin = document.getElementById('muffin'+id);
var q_muffin = document.getElementById('muffin_quantity'+id).value;
if (muffin.checked) charge += q_muffin;
});
window.alert("Your total is: $" + charge);
string str=Convert.toString(checkbox.checked);//int return With Null Value in ""
switch (str.toUpper()) {
case "TRUE":
charge += q_muffin1 * muffin1;
break;
case "FALSE":
charge += q_muffin2 * muffin2;
break;
default:
window.alert("Sorry, we are out of");
}
window.alert("Your total is: $" + charge);
CHECK This
Would like to know how to check true and false and in return give error message if checked and the number is incorrect..
<input name="student1" type="text" size="1" id="studentgrade1"/>
<input name="student2" type="text" size="1" id="studentgrade2"/>
<input name="student3" type="text" size="1" id="studentgrade3"/>
so here we have 3 inputbox , now i would like to check the result by entering number into those inputbox.
studentgrade1 = 78
studentgrade2 = 49
studentgrade3 = 90
<< Using JavaScript >>
So If User entered wrong number e.g "4" into inputbox of (studentgrade1) display error..
same for otherinputbox and if entered correct number display message and says.. correct.
http://jsfiddle.net/JxfcH/5/
OK your question is kinda unclear but i am assuming u want to show error
if the input to the text-box is not equal to some prerequisite value.
here is the modified checkGrade function
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
VAR errText = "";
if (stud1.exists() && (parseInt(stud1.value) == 78){return true;}
else{errText += "stud1 error";}
//do similiar processing for stud2 and stud 3.
alert(errText);
}
See demo →
I think this is what you're looking for, though I would recommend delimiting your "answer sheet" variable with commas and then using split(',') to make the array:
// answers
var result ="756789";
// turn result into array
var aResult = [];
for (var i = 0, il = result.length; i < il; i+=2) {
aResult.push(result[i]+result[i+1]);
}
function checkgrade() {
var tInput,
msg = '';
for (var i = 0, il = aResult.length; i < il; i++) {
tInput = document.getElementById('studentgrade'+(i+1));
msg += 'Grade ' + (i+1) + ' ' +
(tInput && tInput.value == aResult[i] ? '' : 'in') +
'correct!<br>';
}
document.getElementById('messageDiv').innerHTML = msg;
}
See demo →
Try this http://jsfiddle.net/JxfcH/11/
function checkgrade() {
var stud1 = document.getElementById("studentgrade1");
var stud2 = document.getElementById("studentgrade2");
var stud3 = document.getElementById("studentgrade3");
if (((parseInt(stud1.value) == 78)) && ((parseInt(stud2.value) == 49)) && ((parseInt(stud3.value) == 90)))
{
alert("correct");
}
else
{
alert("error correct those values");
}
}