I have a page with a question. The user will have to type the answer to that question in a textbox. I am using a switch statement to generate different feedback to different answers. I already managed to make it case insensitive.
Is there a way to also make it ignore punctuation and spaces?
This is the code I have:
function myFunction() {
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
switch (answers) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
I would like it to accept all the following answers as correct, without having to add extra cases:
"Superman", "superman", "Super Man", "Super man", "Super-Man!", "Super-man"...
You could use a regex to ignore everything else that is not an alphabet.
function myFunction() {
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
answers = answers.replace(/[^a-z]/g, "");
switch (answers) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
You could match only letters and omit unwanted character. Then take convert to lower case.
function myFunction() {
function getLetters(s) { return s.match(/[a-z]/gi).join('').toLowerCase(); }
var text;
var answers = document.getElementById("myInput").value.toLowerCase();
switch (getLetters(answers)) {
case "superman":
text = "That is correct!";
break;
case "batman":
text = "You must be kidding me...";
break;
default:
text = "Wrong answer."
}
document.getElementById("comment").innerHTML = text;
}
<p>Who is Clark Kent?</p>
<input id="myInput" type="text">
<button onclick="myFunction()">Answer</button>
<p id="comment"></p>
use this:
var desired = stringToReplace.replace(/[^\w\s]/gi, '').toLowerCase();
Related
why is this code only giving me the default value
<!DOCTYPE html>
<html>
<body>
<p id= "demo"></p>
<input id="age" />
<button onclick="document.getElementById('demo').innerHTML=text">try it</button>
<script>
var text;
age = document.getElementById('age').value;
switch (age) {
case 10:
text = "diuble";
break;
case 13:
text = "puberty";
break;
case 18:
text = "Beer!";
break;
default:
text = "Looking forward to the Weekend";
}
</script>
</body>
</html>
I have tried changing document.getElementById('age').value to 18, when i do that it gives me the output as beer! but right now its only giving me Looking Forward....
You are not calling a function onclick, and firing the code on document load. The right way to do it would be:
function getText(){
var text;
age = document.getElementById('age').value;
age = parseInt(age)
switch (age) {
case 10:
text = "diuble";
break;
case 13:
text = "puberty";
break;
case 18:
text = "Beer!";
break;
default:
text = "Looking forward to the Weekend";
}
document.getElementById('demo').innerHTML=text
}
<p id= "demo"></p>
<input id="age" />
<button onclick="getText()">try it</button>
<button onclick = "button javascript.js">
What do you drive? </button>
I want the button to run my switch() in the button javascript.js file
var car = prompt('What car?');
switch(car) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
You can put the code in a function inside the javascript. Include the file in script tags and on click of the button, call that function. That will trigger the JS code only on click of the button.
Put this in the HTML,
<script src='button javascript.js'></script>
//Intermediate HTML code
<button onclick = "myButtonFun()">
What do you drive? </button>
And in the Javascript you can put in your code in the function myButtonFun()
function myButtonFun()
{
var car = prompt('What car?');
switch(car) {
case 'ferrari': document.write("you are probs a baller then");
break;
case "porsche": document.write("do you ball hard?");
break;
case "dodge": document.write("american cannot corner");
break;
default: document.write("your car better be a subaru");
}
}
Make your code into a function and, on the button, use
type="button"
and
onclick="yourFunction()"
You need to wrap your script into function and invoke it on button click:
<button onclick = "askForCar();">What do you drive?</button>
var askForCar = function() {
//you script here
};
var askCar = function() {
switch (prompt('What car?')) {
case 'ferrari':
document.write("you are probs a baller then");
break;
case "porsche":
document.write("do you ball hard?");
break;
case "dodge":
document.write("american cannot corner");
break;
default:
document.write("your car better be a subaru");
}
};
<button onclick="askCar();">What do you drive?</button>
Im trying to make some kind of "blog" buttons. I want to click on a button, and then it will write in my textarea for whatever button I clicked. But for some reason, it wont add if I've been writing or done anything in the textarea before I clicked.
<button onClick="knapp('lank')">Länk</button>
<button onClick="knapp('fet')">Fet</button>
<button onClick="knapp('bild')">Bild</button>
<br><br>
<textarea id='knappar' rows="10" cols="50"></textarea>
And my scriptcode is
function knapp(value)
{
var text;
switch(value){
case "fet":
text = '<b></b>';
break;
case "lank":
text = 'Klicka här';
break;
case "bild":
text = '<img src="https://www.hemsida.com">';
break;
}
var pp = document.createTextNode(text);
document.getElementById('knappar').appendChild(pp);
}
So when I click the button, it writes and append. But if I've been writing, or deleting something, it wont work.
I'm fairly new with Javascript, so sorry for noob question.
Try using
document.getElementById('knappar').value += text;
instead of
var pp = document.createTextNode(text);
document.getElementById('knappar').appendChild(pp);
Full Example
function knapp(value) {
var text;
switch (value) {
case "fet":
text = '<b></b>';
break;
case "lank":
text = 'Klicka här';
break;
case "bild":
text = '<img src="https://www.hemsida.com">';
break;
}
var pp = document.createTextNode(text);
document.getElementById('knappar').value += text;
}
<button onClick="knapp('lank')">Länk</button>
<button onClick="knapp('fet')">Fet</button>
<button onClick="knapp('bild')">Bild</button>
<br><br>
<textarea id='knappar' rows="10" cols="50"></textarea>
I am trying to create a normal javascript switch that'll give me an alert message and image based on what the user has selected from a drop down menu
here's what I have so far
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
</head>
<body>
<h1>How are you feeling?</h1>
<img id="feelimg" src="Images/questionSun.jpg" alt="question sun">
<select id="feeling" onChange="changeFeeling();">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
</body>
</html>
No matter what I do it is stuck on case question. It needs to be javascript. I am not allowed to use jquery for this particular problem.
Just move your var declaration inside your function.
The way you have done the var was getting populated with the value once the javascript gets loaded, moving it to the function it will be populated at the onChange event and then the switch works nice.
<script type="text/javascript">
var curFeel = document.getElementById('feeling').value;
function changeFeeling(){
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
Another way that I would recomend is to not use this global variable and just use the parameter using the onchange like that:
<select id="feeling" onChange="changeFeeling(this);">
<option value="question">Question</option>
<option value="happy">Happy</option>
<option value="sad">Sad</option>
<option value="cool">Cool</option>
<option value="unsure">Unsure</option>
</select>
<script type="text/javascript">
function changeFeeling(curFeel){
switch (curFeel.value) {
case 'question': {
document.getElementById("feelimg").src = "Images/questionSun.jpg";
alert("Please make a selection or go back to bed!");
break;
}
case 'happy': {
document.getElementById("feelimg").src = "Images/happySun.jpg";
alert("I am glad you are happy");
return curFeel;
break;
}
case 'sad': {
document.getElementById("feelimg").src = "Images/sadSun.jpg";
alert("I am sorry you are sad");
break;
}
case 'cool': {
document.getElementById("feelimg").src = "Images/coolSun.jpg";
alert("It's great you are feeling cool!");
break;
}
case 'unsure': {
document.getElementById("feelimg").src = "Images/unsureSun.jpg";
alert("I hope you get past that soon!");
break;
}
}
}
</script>
Make your switch variable event.target.value and it will work how you want it to.
To access a global var from inside a function
var curFeel;
function changeFeeling(){
curFeel = event.target.value;
switch (curFeel) {
case 'question': {
....
}
}
}
That way the variable curFeel will be whatever the selected value is globally.
Heres a Codepen
I think Diego Garcia has provided the answer, but I'd like to suggest a simple improvement to the code generally for you to collect a few bonus points (should they be available).
var curFeel; // Value is not being used before changeFeeling function call, so you only need declare it rather than assign a value
function changeFeeling(){
var picture, message; // Declare variables to contain the decided upon image and alert message
var pictureFiles = 'Images/'; // Where your image files are kept, so you don't repeat a dozen times below
curFeel = document.getElementById('feeling').value;
switch (curFeel) {
case 'question': {
picture = "questionSun.jpg";
message = "Please make a selection or go back to bed!";
break;
}
case 'happy': {
picture = "happySun.jpg";
message = "I am glad you are happy";
break;
}
case 'sad': {
picture = "sadSun.jpg";
message = "I am sorry you are sad";
break;
}
case 'cool': {
picture = "coolSun.jpg";
message = "It's great you are feeling cool!";
break;
}
case 'unsure': {
picture = "unsureSun.jpg";
message = "I hope you get past that soon!";
break;
}
}
// Set image and alert message!
document.getElementById("feelimg").src(pictureFiles + picture);
alert(message);
}
Reasons Why:
The above is easier to read
In the event that the ID of the picture element, or the location of the image files, changes you only need to change it in one place rather than a dozen
And the same if the behaviour around the message alert changes, e.g. instead of using the alert() function, the message is inserted into a div element on the page instead for example (only one change required rather than a dozen)
Hope this helps.
I'm new to Javascript and don't understand the following behaviors.
When the textarea is empty, the "process" code doesn't recognize it as null, and doesn't prompt for text.
When there is text in the textarea, the "process" code does not display the text in the alert. It seems this may be a scope problem I think all my variables are global.
HTML code:
<input type="button" name="btnProcessTA" onclick="myTextArea('process')" value="Process Text Area" />
<input type="button" name="btnClearTA" onclick="myTextArea('clear')" value="Clear Text Area" />
<form id="formExample" action="" method="get">
<label for="textAreaField">A text area field</label>
<textarea name="textAreaField" id="textAreaField" rows="4" cols="50"></textarea>
</form>
Javascript code:
<script type="text/javascript">
function myTextArea(op)
{
oTextArea = document.getElementById("textAreaField");
textAreaValue = oTextArea.value;
alert(op + "\n" + oTextArea + "\n" + textAreaValue);
switch (op){
case "clear":
oTextArea.value = "";
alert("Clearing");
break;
case "process":
if (textAreaValue = "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;
default : alert("unknown op code");
}
}
</script>
Change
if (textAreaValue = "")
to
if (textAreaValue === "") // or ==
You are performing assignment instead of doing a comparison.
To compare, you have to use == instead of = :)
case "process":
if (textAreaValue == "")
alert("Would you please enter some text?");
else
alert("You entered:\n\n" + textAreaValue);
break;
if (textAreaValue = "")
The single equal sign in the if statement is interpreted as an assignment (It doesn't throw an error because technically it's correct syntax, but many people make this mistake by using a single equal sign instead of the double equal sign). The correct syntax would be the triple equal sign if you are intending to compare instead of assign.
if (textAreaValue === "")