<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>
Related
I am trying to put different buttons with same function in switch statement. Every button needs to call same function but with different switch parameter.
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">
SQRT
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left:
100px;">
SIN
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left:
100px;">
COS
</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left:
100px;">
ROUND
</button>
And here is JS code,
<script>
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
if(x > 0 && x < 1000){
switch(x){
case 0:
document.getElementById("btnSQRT");
document.write("nesta");
break;
case 1:
document.getElementById("btnSIN");
document.write("nesta");
break;
case 2:
document.getElementById("btnCOS");
document.write("nesta");
break;
case 3:
document.getElementById("btnROUND");
document.write("nesta");
break;
}
}
else{
alert("Thats not a wanted number");
}
}
</script>
Change all of your onclick="myFunction()" to onclick="myFunction(this)" - that will allow you to test for the switch in myFunction - in which case you want to switch on the button ID rather than the prompt value.
function myFunction(el){ // el will be the button that called the function
var x = prompt("Input number between 1 i 999");
if(x > 0 && x < 1000){
switch(el.id){ // switching on the ID of the button which tells us which math to use
case 'btnSQRT':
alert('The square root is ' + Math.sqrt(x));
break;
.....
I am not sure what 'nesta' and document.write was for, so I removed them here.
You are trying to switch between INT numbers, and "prompt" return a STRING. So, It will never get in any switch statement. To solve this, I just added a "parseInt()" in your prompt variable.
I changed "document.write('nesta')" by inner.HTML('nesta'), so, it changes the text in the button. But, to change the text inside the button, you got to set a variable to each button.
HTML:
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSQRT">SQRT</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnSIN" style="margin-left: 100px;">SIN</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnCOS" style="margin-left: 100px;">COS</button>
<button type="submit" onclick="myFunction()" class="dugme1" id="btnROUND" style="margin-left: 100px;">ROUND</button>
JS:
function myFunction(){
var x = prompt("Input number beteen 1 i 999");
var x = parseInt(x);
if(x > 0 && x < 1000) {
switch(x){
case 1:
var nesta = document.getElementById("btnSQRT");
nesta.innerHTML = 'nesta';
break;
case 2:
var nesta =document.getElementById("btnSIN");
nesta.innerHTML = 'nesta';
break;
case 3:
var nesta = document.getElementById("btnCOS");
nesta.innerHTML = 'nesta';
break;
case 4:
var nesta =document.getElementById("btnROUND");
nesta.innerHTML = 'nesta';
break;
}
} else {
alert("Thats not a wanted number");
}
}
Here you have:
One event listener for all buttons.
getting the "value" from the button using the attribute id. An alternative could be to use a data-attribute (like I did with the 2ed button).
A switch statement for handling what to do next.
It is not completely clear for me if the switch statement is the right approach here. Please comment if you have questions.
document.addEventListener('DOMContentLoaded', e => {
let buttons = document.getElementById('buttons');
let output = document.getElementById('output');
buttons.addEventListener('click', e => {
if (e.target.nodeName == 'BUTTON') {
switch (e.target.id) {
case 'btnSQRT':
output.innerHTML = 'You clicked SQRT';
break;
case 'btnSIN':
output.innerHTML = 'You clicked SIN';
break;
case 'btnCOS':
output.innerHTML = 'You clicked COS';
break;
case 'btnROUND':
output.innerHTML = 'You clicked ROUND';
break;
}
}
});
});
div#buttons {
display: flex;
justify-content: space-between;
}
<div id="buttons">
<button id="btnSQRT">SQRT</button>
<button data-func="SIN" id="btnSIN">SIN</button>
<button id="btnCOS">COS</button>
<button id="btnROUND">ROUND</button>
</div>
<div id="output"></div>
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>
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();
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 need to - Create a HTML form with a text entry field and a button.. When a number is entered in the text entry field and the button clicked a Javascript function called DayOfTheWeek() is invoked. This function uses a switch statement to determine the day of the week corresponding to the number entered, i.e if the number entered is 1 the message “It’s Monday” is displayed, if the number entered is 2 the message “It’s Tuesday” is displayed and so on. If a number which is not between 1-7 is entered then the message “Not a valid day of the week” is displayed.
my html
<input type="text" name="text1"/>
<input type="button" value="Click me" onclick="days(text1.value);"/>
my java script
function days(dayOfTheWeek)
{
switch (dayOfTheWeek) {
case “1”:
alert(“It\’s Monday”);
break;
case “2”:
alert(“It\’s Tuesday”);
break;
case “3”:
alert(“It\’s Wednesday”);
break;
case “4”:
alert(“It\’s Thursday”);
break;
case “5”:
alert(“It\’s Friday”);
break;
case “6”:
alert(“It\’s Saturday”);
break;
case “7”:
alert(“It\’s Sunday”);
break;
default:
alert(“Not a valid day”);
break;
}
}
PLEASE HELP I keep getting an error with firebug saying days is not defind
function days(dayOfTheWeek) {
var weekday=new Array(7);
weekday[0]="Sunday";
weekday[1]="Monday";
weekday[2]="Tuesday";
weekday[3]="Wednesday";
weekday[4]="Thursday";
weekday[5]="Friday";
weekday[6]="Saturday";
var n = weekday[dayOfTheWeek];
return n;
}
Your updated code
<input type="text" name="text1" id="text1" />
<input type="button" value="Click me" onclick="javascript:days(parseInt(document.getElementById('text1').value));" />
<script language=javascript>
function days(dayOfTheWeek)
{
switch (dayOfTheWeek) {
case 1:
alert("It\’s Monday");
break;
case 2:
alert("It\’s Tuesday");
break;
case 3:
alert("It\’s Wednesday");
break;
case 4:
alert("It\’s Thursday");
break;
case 5:
alert("It\’s Friday");
break;
case 6:
alert("It\’s Saturday");
break;
case 7:
alert("It\’s Sunday");
break;
default:
alert("Not a valid day");
break;
}
}
</script>