html javascript reverts to default after javascript has run - javascript

I am learning javascript and we have been given the task of changing image / colour of paragraph from the click of the button. My code works but I had to add an alert() to stop it to show this as it reverts to default image/colour as soon as it runs.
function changeImage() {
var myTag=document.getElementById("imageColour");
myTag.src = "images/white.jpg";
var x = document.getElementById("demo");
x.style.color = "red";
// Had to add this to see change
alert("Has reached changeImage()");
}
<html lang="en">
<head>
<meta charset="utf-8"/>
<script type="text/javascript" src="script.js"></script>
<title>Exercise 3</title>
</head>
<body>
<h3>Exercise 3</h3>
<img src="images/black.jpg" id="imageColour"/>
<form>
<button type="submit" id="mySubmitButton">Change Colour</button>
</form>
<p id="demo">Click the button to change the colour of this paragraph.</p>
</body>
</html>
<!--javascript-->
<script type="text/javascript">
document.getElementById("mySubmitButton").addEventListener("click", changeImage);
</script>
Any help appreciated.

You are submitting a form. That causes the page to be reloaded and reset.
Use type="button" (and you might as well remove the form entirely while you are at it) or call preventDefault on the event object (the first argument to changeImage).

Related

Val(" ") Not Removing Text From Text Box

In my HTML file, I have code which takes input in a text box and then displays it on the page without re-loading the page. I am using JQuery to do this. However, the line in the code which is supposed to remove the text from the text box is not working. Please see below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/styleblock.css">
<script type=text/javascript src="{{url_for('static', filename='jquery.js')}}">
</script>
<script type="text/javascript">
function placetextfromboxes() {
event.preventDefault();
var textFrombox = $("#yg").val();
$("input.submit").val("");
$("#word").html(textFrombox)
}
</script>
</head>
<body>
<form action="/" method="post">
<p>Name:</p>
<textarea id="yg" name="nm"></textarea>
<p><input type="submit" value="Submit:" onclick="placetextfromboxes(event);" /></p>
<p id="word"></p>
</form>
</body>
</html>
Text from "" is taken to the placetextfromboxes function and put in the variable "textFrombox". However, the line "$("input.submit").val("");" is supposed to erase the text from the box but it is not being erased. Is there anything that I am missing?
As per azro's suggestion in the comments, changing $("input.submit") to $("#yg") produces the effect you're looking for.
For convenience, the correction is offered in the snippet below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="/static/styleblock.css">
<script type=text/javascript src="{{url_for('static', filename='jquery.js')}}">
</script>
<script type="text/javascript">
function placetextfromboxes() {
event.preventDefault();
var textFrombox = $("#yg").val();
$("#yg").val("");
$("#word").html(textFrombox)
}
</script>
</head>
<body>
<form action="/" method="post">
<p>Name:</p>
<textarea id="yg" name="nm"></textarea>
<p><input type="submit" value="Submit:" onclick="placetextfromboxes(event);" /></p>
<p id="word"></p>
</form>
</body>
</html>
It appeared to me as though $("input.submit") had been intended to select the submit button.
Changing the value to $("input") or $("input[type=submit]") successfully selected it but, as you may guess, it simply erased the text in the button when clicked.
Changing to $("#yg").val(""), successfully erases the text in the textarea and does not affect the value stored in the textFrombox variable.
input.submit would target an input element with class submit. What you have instead is attribute type of value submit. Therefore, to select this you'd need to do input[type=submit].
But it looks like you just want $('#yg').val('').

JavaScript & HTML: Event Listener Is Not Producing Text Alert As Expected; ReferenceError: button is not defined

I am trying to implement an Event Listener on a DOM (webpage) that produces an alert when a user submits an input inside an input box.
Here is my HTML code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Examples</title>
<!-- <link rel="stylesheet" href="main.css"></link> -->
</head>
<body>
<h1 id="title">This is my Title </h1>
<input type="text" placeholder="some text">
<button id='submit-text-btn'>Submit</button>
<p>
This is the text that is going to display.
I really need to figure out how to balance the next week out.
Maybe just pour myself into this and finish recursion, classes, plus guessing game quickly.
</p>
<script src="dom.js"></script>
</body>
</html>
Here is my JS code:
function getInputAndUpdate(inputElement){
const text = inputElement.value;
inputElement.value = '';
alert(text);
}
button.addEventListener('click', function(){
const inputElement = document.querySelector('input');
getInputAndUpdate(inputElement);
});
Below is a screen shot of my resulting webpage:
My problem is nothing happens when I type text into the input box and click submit. No Alert message pops up at all.
Below is the error I see in the console:
dom.js:10 Uncaught ReferenceError: button is not defined
That's because the button variable you're adding the event listener on hasn't been initialised.
To get a reference of an element in the DOM, use document.getElementById (which retrieves the element that has the ID - note that IDs must be unique), document.getElementsByClassName (which retrieves all elements that have the class) or document.getElementsByTagName (which retrieves all elements by their tag name).
In this case, since you're already using an ID on the button, you can retrieve the element with document.getElementById:
function getInputAndUpdate(inputElement){
const text = inputElement.value;
inputElement.value = '';
alert(text);
}
var button = document.getElementById('submit-text-btn');
button.addEventListener('click', function(){
const inputElement = document.querySelector('input');
getInputAndUpdate(inputElement);
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>DOM Examples</title>
<!-- <link rel="stylesheet" href="main.css"></link> -->
</head>
<body>
<h1 id="title">This is my Title </h1>
<input type="text" placeholder="some text">
<button id='submit-text-btn'>Submit</button>
<p>
This is the text that is going to display.
I really need to figure out how to balance the next week out.
Maybe just pour myself into this and finish recursion, classes, plus guessing game quickly.
</p>
<script src="dom.js"></script>
</body>
</html>
Just select your button like this
const button = document.getElementById("submit-text-btn");

Changing elements in an HTML file using javascript onclick event

I've been learning HTML and CSS this semester and originally started to code my project in HTML and CSS, but in order for my project to work, I had to link HTML pages to each other. It ended up making a lot of HTML pages just to change one line of text. I've been trying to get a handle on JavaScript to make my project more efficient. My HTML code looks like this:
<!doctype html>
<html>
<head>
<meta charset=utf-8>
<title>Oakwood</title>
<meta name="viewport" content="width=device-width; initial-scale=1.0;">
<link rel=stylesheet type=text/css href=default.css>
</head>
<body>
<div id=back></div>
<div id=drdick></div>
<div id=choice></div>
<div class="typewriter">
<script src="run.js"></script>
<p id=text>While out running someone says “Hi” causing you to trip. He helps you up.</p>
</div>
<div id=move>
<button type="button" onclick="changeThis()">Next</button>
</div>
</body>
</html>
My Javascript Looks like this:
var quoteIndex = 0;
var quotes = [
"Thank you.",
"Are you ok?",
"Yes, I’m not normally this clumsy"
];
function changeQuote() {
++quoteIndex;
if (quoteIndex >= quotes.length) {
quoteIndex = 0;
}
document.getElementById("text").innerHTML = quotes[quoteIndex];
}
function showPic()
{document.getElementById("drdick").src="img/drdickab.png";}
function changeThis() {
changeQuote();
showPic();
}
when I test my code my quotes update how I want them to. My picture does not show up at all. Is there something I am missing when it comes to how HTML and Javascript interact? I have been looking through the forums to figure out what I have wrong, and I haven't been able to figure that out.
Your image is not displaying because you did not specify your image anywhere in your markup, and your javascript is also not enough. But try this inside your body tag:
<body>
<!--replace your button with this code.-->
<div id=move>
<button type="button" onclick="showMyImage();" value="Next"></button>
</div>
<!--I assumed you will display the image just below your button, note that initially your image is hidden and displayed on button click event-->
<div>
<img id="myImage" src="img/drdickab.png" style="visibility:hidden"/>
</div>
</body>
.
<!--There's really no need to have multiple scripts, just one will do the job-->
<script type="text/javascript">
function showMyImage(){
document.getElementById('myImage').style.visibility="visible";
}
</script>

innerHTML is not displaying properly

The problem I'm having is, if the user leaves the userdata input blank, I want it to target that input and display text, notifying them that it's a required field.
I'm using innerHTML to send the message to a div or directly to the input field but nothing is displayed. I have also tried to use <p>, <span> and that did not work either. Any help is appreciated.
<!doctype html>
<html>
<head>
</head>
<body>
<form>
<input type="text" id="user1">
<div id="error"></div>
<button onClick="test()">Work</button>
</form>
<script type="text/javascript">
function test(){
var userdata = document.getElementById("user1").value;
if(userdata == ""){
document.getElementById("error").innerHTML="Please fill in Blanks";
}
}
</script>
</body>
</html>
Just change your button line in this way:
<button onClick="test();return false;">Work</button>
InnerHTML was working fine, but the default behaviour of the button was making a 'POST' request, making the page to refresh erasing the innerHtml changes. The return false statement disable this default behaviour making your code to work as it's supposed to do.
It's tested and working.
Hope It helps.
Here is the JSBIN
HTML
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
<form>
<input type="text" id="user1">
<div id="error"></div>
<button onClick="test();return false;">Work</button>
</form>
</body>
</html>
And in JavaScript add else condition also
if(userdata === ""){
document.getElementById("error").innerHTML="Please fill in Blanks";
} else{
document.getElementById("error").innerHTML="";
}

Getting HTML Parent Window Won't Work. Suggestions?

I have the following two HTML Documents:
Main.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
var ExamId = "001A";
function open_exam()
{
window.open("exam.html")
}
</script>
</head>
<body>
<input type=button value="Open Exam" onclick="open_exam()">
</body>
</html>
Exam.html
<html lang="eng">
<head>
<title>JavaScript Example</title>
<script type="text/javascript">
function setParentInfo()
{
window.parent.document.ExamID = '001B';
}
</script>
</head>
<body>
<p>Welcome to the Exam!</p>
<input type=button value="Set Parent Info" onclick="setParentInfo()">
</body>
</html>
Main.html brings up Exam.html via the input button. From inside Exam.html I would like to change the variable ExamID on the parent document (i.e.: Main.html). I'm trying to do this via the JavaScript function: setParentInfo().
The above code is not working. Can someone help me come up with the correct code?
Thanks So Much!
Variables are assigned on the window object, not the document object.
Since the value is already set, you can instead read the existing value to verify it:
alert(window.parent.ExamId); // == "001A"
Variable is declared and assigned in parent window so you get reference from your child window.
you can test using alert statement:
alert(window.parent.document.ExamId);
//output::001B

Categories