Images from string function - javascript

I'm trying to make a magic eight ball simulation, but it's not working for me. The inspector element in Chrome shows no errors, so I'm confused why it won't work. Any suggestions would be greatly appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Project 4: Consistent</title>
<!-- This part is the function to create my magic eight ball that will randomly give a result, but for certain questions,
it will provide the same answer always to fool their minds. -->
<script>
var answerMap = {}
var images = ['eightBallYes.png', 'eightBallNo.png', 'eightBallMillionYears.png', 'eightBallAskLater.png', 'eightBallReally.png'];
//I actually had a little bit of difficulty with this part of the project.
//The answer.search method you showed us in class for some reason is not working for me.
//I worked with the GTF on this part
function eightBall() {
var answer = document.getElementById("answerBox").value;
answer = answer.toLowerCase();
if (answer.search(/[r]/) > 0 ) {
var yes = '../Images/eightBallYes.png'
return yes;
}
if (answer.search(/[m]/) > 0 ) {
var no = '../Images/eightBallNo.png'
return no;
}
}
window.onload = alert('Welcome to my Project 4')
</script>
</head>
<body>
<body style="background:#EEEE17">
<!-- This part of the page will simulate a magic eight ball that will provide at least 4 answers.
When certain questions are asked, it will return the same answers. This is honestly a pretty cool project to work on. -->
<div style="text-align:center">
<h1>Project 4: Booyah!</h1>
<img src="../images/eightBallTemplate.png" >
<h2>Magic 8-Ball Game</h2>
<input type="text" id="answerBox" value="Please ask a question">
<input type="button" value="Submit for Magical Results" onclick='eightBall()'/>
<div id="myOutput"></div>
<hr>
Old MacDonald In-Class Activity
<br>
Parameter In-Class Activity
<br>
jQuery In-Class Activity
<br>
String In-Class Activity
<footer>
<p>
© Copyright by Alan Sylvestre
</p>
</footer>
</div>
</body>

You aren't doing anything with the return value of your function.
You probably want to assign it to the <img> tag's src property.

The problem I see is that you are calling the eightBall function when the button is clicked and the right value is chosen, but you are not doing anything with it, e.g. appending a node in the myOutput div.
You also have two body tags.

Related

2 separate scripts in HTML/JS are interfering with each other [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I am learning HTML/JS and I am having trouble with this script. I am practicing making buttons that preform actions but when I got to the the part of where clicking text doing actions like changing innerHTML. I have tried moving the script to a different location on the page but with no luck anytime I press the element that changes text it makes the other script do the action but not the one I clicked. I am referring to when I use
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
I am only having trouble with both myFuntion() scripts. Please help. See issue for yourself by loading it in an editor.
<!DOCTYPE>
<html>
<center><font face = "Canela" fontSize = "35px" style = "color: darkblue"><h1>Just practice</h1></font></center>
<body>
<font face = "Didot"><h1>Change text</h1></font>
<p id="mill">This text will change</p>
<button type = "button" onclick = 'document.getElementById("mill").innerHTML="Changed!"'>Click to change!</button>
</body>
<body>
<font face = "Papyrus" ><h1>This will make text reappear</h1></font>
<p id="disa" style = "display:none">This text will be reappear</p>
<button type = "button" onclick = "document.getElementById('disa').style.display='block'">Click to reappear</button>
</body>
<body>
<font face = "Verdana"><h1>This will make text disappear</h1></font>
<p id="deps">This text will go away when you click that button</p>
<button type = "button" onclick = "document.getElementById('deps').style.display='none'">Click to make this text go away!</button>
</body>
<body>
<h1>This will Change the font size</h1>
<p id="clas">This should become bigger</p>
<button type = "button" onclick = "document.getElementById('clas').style.fontSize='45px'">Click to make the size bigger</button>
</body>
<body>
<h1>Click to change text color</h1>
<p id="siaz" onclick="myFuntion()">Click me to make my text change color!</p>
<script>
function myFuntion() {
document.getElementById("siaz").style.color='red';
}
</script>
</body>
<body>
<h1>Clicking the text will change the text</h1>
<p id="home" onclick = "myFuntion()">Click me, I dare you</p>
<script>
function myFuntion() {
document.getElementById('home').innerHTML="Go away"
}
</script>
</body>
</html>
You should have only one script, but you can put in as many functions as you want. You can have a changeColor function, a changeFont function (you can name then whatever you want but should have an appropriate description so it's easier to read it).
<p id="siaz" onclick="changeColor()">Click me to make my text change color!</p>
<p id="home" onclick="changeText()">Click me, I dare you</p>
<script>
function changeColor() {
document.getElementById("siaz").style.color='red';
}
function changeText() {
document.getElementById('home').innerHTML="Go away";
}
</script>
Irrespective of what you are trying to achieve, that's not the good practice to follow.
Even if you are learning
Learn the right practices at the start itself. So, a few changes needed
There can only be 1 <body> tag
Follow proper naming conventions - Method name should be a verb e.g.: changeFontColor(), changeFontSize(), etc.
Seperate html templates, styling and scripts - Use css instead of elemtents like font. No inline css or internal javascript. Keep it in separate file or in a single separate section.
Code should be properly indeneted
As you are new to this, I have shared a template for designing html pages which you could refer to start with
<!DOCTYPE>
<html>
<head>
<style>
<!-- All css styles goes here -->
</style>
</head>
<body>
<!-- All html code goes here -->
<script>
<!--All scripts goes here -->
</script>
</body>
</html>
Solution: If you could just change the
myFunction()
which changes the color to
myFunction1 or anything other than "myFunction"
at both the places (the function definition where you change the color and at the place where you are calling it, the onclick for color change) then it will start working.
Reason: As Keith said in the comments, in the global scope, we shall have unique function names, otherwise, the last one defined takes the precedence.
Best,
Sumit

How to switch inputted text between 2 colored boxes in html

So far I only have the code that is able to make 2 boxes, made the 4 buttons, but only 1 button actually does something, and that is the start button where a there is a popup that asks for a name, and after you input that name, it will appear in the first box.
<html>
<head>
<script>
function myTask1() {
var sentence = prompt("Please enter a name");
var arrSentence = sentence.split(" ");
if (arrSentence != null) {
document.getElementById("answer1").innerHTML = arrSentence.sort(); //so we can use Array.sort() function
}
console.log(sentence);
return sentence;
}
function myFunction() {
var x = document.getElementById()
}
</script>
<style> </style>
</head>
<body>
<p><button type="button" onclick="myTask1()">Click me!</button></p>
<button type="button" onclick="ClearFields();">Clear</button>
<button type="button" onclick="myFunction()"> --> </button>
<button type="button" onclick="myTask4()"><-- </button>
<div clas="box" style="background-color:red; height:200px; margin:20px auto;">
<center>
<p id="answer1"></p>
<center>
</div>
<div class="box1" style="background-color:grey; height:200px; margin:20px auto;"> </div>
</body>
</html>
I've made some demo code for you. I assume that you're a beginner because the question is basic. This is not a problem though, starting something new is great. You can find the answer on the internet and the best programmers are often people who are good with Google. But I hope by showing you the solution anyway you get a feeling for structure. Try to understand every line. Try write it from scratch afterwards anyway. It's a great exercise.
Code: https://github.com/Bunpasi/stackoverflow-answers/blob/master/js-listbox-selector/index.html
Some things to notice:
- I've put the script in the footer so it doesn't interfere with the loading time of the page.
- I've put all code in an anonymous function to avoid global functions.
- I changed clas to class.
- I've used event listeners instead of even attributes.
- I didn't duplicate the logic for both boxes but used one function which I can use on both.
After your understand the code, there are some things you can improve on this code.
- Make sure the selection doesn't go away after the update. You can store this in the data as well. Right now the data is an array of ID's, but you can turn it into an array of objects containing even more important data, like whether it's selected.
- Move the style from the elements to the header.
Don't be discouraged by down votes.
Good luck!
Update
If you want to move all names all the time. This is what you need to do.
This line looks for all selected elements:
var selectedElements = boxes[fromId].querySelectorAll('.list_item.selected');
Remove the selected .selector:
var selectedElements = boxes[fromId].querySelectorAll('.list_item');

What is wrong with this basic Javascript code? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I'm watching a basic tutorial series on javascript and have been stuck on this super simple script for like close to 30 minutes now. I used an html validator and it all checks out with no errors. However, the code is still not behaving how it should according to the video.
When you type "click me" its supposed to show a dialog box saying 'please enter a real value into the box'. And when you enter a value in the field, it's supposed to substitute the title for whatever you entered.
Sorry for the simple nooby question
EDIT AGAIN: Thanks Arby. That got it working.
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script type="text/javscript">
function substitute () {
var myValue = document.getElementById(myTextBox).value;
if (myValue.length == 0){
alert('Please enter a real value in the text box!');
return;
}
var myTitle = document.getElementById('title');
MyTitle.innerHTML = myValue;
}
</script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<input type="submit" value="Click Me" onclick="substitute()" />
</body>
</html>
I found some issues with your code, just simple stuff that every beginner goes through (I did), I'll bullet them off:
MyTitle isn't myTitle, JavaScript variables are case-sensetive.
You should stay away from the onclick attribute; he's a bad influence. The point, inline JS is generally not a good idea.
So I added an event listener event instead: [...].addEventListener("click", callback);
Your DOM request to the input box used an undefined variable/object/etc. called myTextBox, instead of a string "myTextBox".
Anyway, I made a JSFiddle for the code, so I could test it, so here is the link to the code with the edits I explained above: https://jsfiddle.net/Lktzw0Lh/
A slightly different approach - since you list jQuery in the tags for this - i have rejigged the code to take advantage of it. I put an onclick event handler on the button which, when clicked gets the value of the textbox and if it is empty - gives the alert. If it is not empty - it swaps the h1 text for the entered text and clears the text input and gives it focus so that you can re-enter new content.
Note that the click handler is in the javascript section and not inline js and also that with jquery - you can chain together commands that affect the same element.
$(document).ready(function(){
$('#testButton').click(function(){
var myValue = $('#myTextBox').val();
if (myValue == ''){
alert('Please enter a real value in the text box!');$('#myTextBox').focus()
}else{
$('#title').text(myValue);$('#myTextBox').val('').focus()
}
})
})
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<h1 id="title">JavaScript Example</h1>
<input type="text" id="myTextBox" />
<button id="testButton" type="button">Click Me</button>
</body>
</html>

Home work help I am stuck at NUmber 6 Window.prompt() step

Here is my coding.. What have I done wrong. I am on number 6 and it is not working Can someone please look at this and give me some help.?
Thanks
<html>
<head>
<title> My Homework </title>
</head>
<body>
<div style="width:400px; height:200px" id="firstdiv">
<br /> <br /><center>Well Hi there! <br/> Answer the prompt to see what happens next.</center>
</div>
<script type="text/javascript">
var moquestion = window.prompt("What is the capital of Missouri?","");
if (moquestion.length < 1) {
<div style="width:400px; height:200px" id="sorrydiv">
<br /> <br /> <h1><center>Sorry you don't feel like playing.<br />The capital of Missouri is Jefferson City</center></h1>
</div>
}
</script>
</body>
</html>
Below is the assignment
Create a webpage with all the basic HTML tags.
Inside the <body>, create a <div> tag with an element id.
Insert some text into the <div> tag.
Add your script below this <div> so that it will not attempt to run until the has loaded.
Use the window.prompt method to ask “What is the capital of Missouri?” Ensure that no default answer is displayed for the user.
Check to make sure the length property of the returned string is not less than 1. If it is empty, write something like the following into the <div> tag: “Sorry you don’t feel like playing. The capital of Missouri is Jefferson City.”
If the string is not empty, use the window.confirm method to ask the user: “Is that your final answer?”
If they confirm, write a string similar to the following into the tag: “The capital of Missouri is” + myanswer + “. So says you.”
If they cancel, ask the question again: “Well then what is the capital of Missouri?” This time, write the answer without error checking.
The main problem with your code is that you are using HTML-Code within your JavaScript code.
The <script type="text/javascript">-tag tells your browser: Execute the next block using your default JavaScript-Engine. But JavaScript Engines aren't able to render or even understand HTML Code.
Start creating a simple template:
<!DOCTYPE html>
<html>
<head>
<title>Homework No. 6</title>
</head>
<body>
<!-- place the script at the bottom to execute
AFTER the whole page has loaded. -->
<script type="text/javascript">
// create the DIV Tag and insert it
// Answers: question 2 & 3
// THIS IS WHERE THE HTML-ELEMENT KICKS INTO THE PAGE
var div= document.createElement("div");
div.innerHTML = "Lets play!";
div.id = "questionContainer";
// Insert the element into the body
document.body.appendChild(div);
var question = window.prompt("What is the capital of Missouri", "");
// check if the question is empty
if (question.length < 1 || typeof question === "undefined") {
div.innerHTML = "Sorry you don't feel like playing :(";
return;
}
// check if user is sure (and repeat the question if he's not.)
if (!window.confirm("Are you sure?"))
question = window.prompt("What is the capital of Missouri", "");
div.innerHTML = "The capital of Missouri is: " + question + " as you told me.";
</script>
<body>
</html>
This should solve the problem. Just remember: Do not mix JavaScript and HTML.
Also: Check out this jsFiddle to view it in action: http://jsfiddle.net/du4CH/
It doesn't mean write a new div tag, it means to change the contents of the tag you've already written, the one you called "firstdiv".
Point 6 is actually saying to "write it into the div tag". Assuming that it means the div that you created earlier you should be looking at locating the div on the document and then writing to its innerHTML. Something like
if (moquestion.length < 1) {
document.getElementById("firstdiv").innerHTML="Sorry you don't feel like playing";
}
should do the trick.

Show 2nd div when radio button checked

Im trying to make a contact form where people will check either "one way" ticket or "roundtrip".
The first "one way" is checked when user reach the contact form and one(1) date field is shown, but if "roundtrip" is checked i want a 2nd date field to be shown with a return date.
Any ideas?
Simply observe the onchange event for the radio button. When it reaches you can check weather single trip or round trip is selected and then show / hide the div with the return date fields.
<!DOCTYPE html>
<head>
<script>
function hdl_change(e) {
document.getElementById('date2').style.visibility =
e.checked && e.id == 'opt_2' ? 'visible' : 'hidden';
}
</script>
</head>
<body>
<form name="myForm">
<input id="opt_1" type="radio" name="trip" value="oneway" onchange="hdl_change(this)"> One way<br>
<input id="opt_2" type="radio" name="trip" value="round" onchange="hdl_change(this)"> Roundtrip<br>
</form>
<div id="date1"> date 1 stuff ...</div>
<div id="date2" style="visibility:hidden"> date 2 stuff ...</div>
</body>
</html>
You would need to use javascript and on-event handlers to accomplish that, as such dependent/binding functionality doesn't come with the regular html form elements (To avoid confusion: same goes for it's potential children).
This answer will give you a pretty good hint how to do it as it answers a question related to a similar problem/request: https://stackoverflow.com/a/5137316/1093284
Update:
As you don't seem very experienced, here's a most simplistic example:
<!-- include jquery.js library first (http://jquery.com/) -->
<script src="jquery.js"></script>
<!-- then work the magic -->
<script>
$(document).ready(function(){
$('#inputB').hide;
$('#checkboxA').click(
function(e){
$('#inputA').show;
$('#inputB').hide;
});
$('#checkboxB').click(
function(e){
$('#inputB').show;
$('#inputA').hide;
});
});
</script>
And if you're fit enough to go pro with jQuery, check the other answer here on this page at https://stackoverflow.com/a/11743381/1093284
Last but not least, I think the answer here at https://stackoverflow.com/a/11743482/1093284 provides the best solution, as it's small and does not require a full-blown 32kb javascript library. On the other hand, inline javascript is actually a no-go. Whatever... it's the users that count and they will prefer a quicker-loading page over nicely coded stuff behind the curtains.

Categories