It looks good, but it's not returning any values.
Any ideas?
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<style type="text/css">
.out {
height: 22px;
width: 100px;
border:solid 1px;
margin: 4px;
padding: 3px;
line-height: 22px;
}
form input {
display: block;
}
</style>
</head>
<body>
<form>Number 1
<input type="text" id="firstNumber">Number 2
<input type="text" id="secondNumber">Number 3
<input type="text" id="thirdNumber">
<input type="button" value="Add Total" onclick="addIt()">
<div class="out" id="Total"></div>
<input type="button" value="Multiply Total" onclick="multiply()">
<div class="out" id="multiplyresult"></div>
<input type="button" value="Ave Total" onclick="averesult()">
<div class="out" id="averesult"></div>
</form>
</body>
</html>
<script type="text/javascript">
var result = getId('Total'),
multiplyresult = getId('multiplyresult'),
n1, n2, n3;
function getValues() {
n1 = getId('firstNumber').value, n2 = getId('secondNumber').value, n3 = getId('thirdNumber').value;
}
console.log((n1) * (n2) * (n3));
window.addIt = function() {
getValues();
result.innerText = (+n1) + (+n2) + (+n3);
};
window.multiply = function() {
getValues();
multiplyresult.innerText = (n1) * (n2) * (n3);
};
window.average = function() {
getValues();
averesult.innerText = (n1) + (n2) + (n3) / 3;
};
function getId(x) {
return document.getElementById(x);
}
</script>
I also was trying to figure out how to return and average value of the three numbers.
But as I am a total novice, I do not know how to do this.
The add and multiply functions are now working, but not the average.
Thanks in advance.
The average has to be calculated like so:
window.average = function() {
getValues();
averesult.innerText = ((n1) + (n2) + (n3)) / 3; //Note brackets around n1->n3
};
And your call to averesult() needs to be changed to average()
The problem is that you ran the script as soon as the page loaded, before all the elements had loaded. Because of that, you were trying to access elements that did not exist yet, and would not exist until the page had finished loading. This can be solved in one of two ways. The first way is wrapping it in a window.onload, and the second way is just moving the <script></script> tags to the end of the <body>
Related
I have an HTML form that will contain predefined values that the user will have to confirm by editing their contents, if needed.
I would like to perform a constant check so that the color background of every cell changes accordingly to its content.
For example, if the cell is empty, its background should be red. Later on I will add more check, for example if it contains the string "MISSING VALUE" it should be yellow and so on.
This is an example of my form and the code I'm trying to execute:
<!DOCTYPE html>
<html>
<style type="text/css">
table.first {
display: table;
table-layout: auto;
float: none margin-left: auto;
margin-right: auto;
}
.table_element {
display: table-cell;
}
</style>
<table class="first">
<div class="table_element">
<p style="text-align: center;">First Name:<br><input name="import_date_visit" id="subEmail" type="text" required size="25" onchange="checkFilled();" value="Claudio"></p>
</div>
<div class="table_element">
<p style="text-align: center;">Last name:<br><input name="import_date_visit" type="text" required size="25" onchange="checkFilled();" value="MISSING VALUE"></p>
</div>
</table>
<script type="text/javascript">
function checkFilled() {
var inputVal = document.getElementsByClassName("table_element");
for (var i = 0; i < inputVal.length; i++) {
document.writeln((i + 1) + ": " + inputVal[i].value);
}
for (var i = 0; i < inputVal.length; i++) {
if (inputVal[i].value == "") {
inputVal[i].style.backgroundColor = "red";
} else {
inputVal[i].style.backgroundColor = "white";
}
}
}
checkFilled();
</script>
</html>
What I don't understand is how to get the value of the string inside the div element. As you can see, I'm trying to print it as a debug, and I'm expecting to get the values Claudio and MISSING VALUE, but all I get is undefined. I suppose it should be pretty straightforward to get the content of a cell, so I assume I'm missing something very obvious.
Thanks for the help.
First find input element inside your div element and then use value property on it.
function checkFilled() {
const divEle = document.getElementsByClassName("table_element");
for(let i = 0; i < divEle.length; i++) {
const inputVal = divEle[i].children[0].children[1];
if (inputVal.value == "") {
inputVal.style.backgroundColor = "red";
} else if (inputVal.value == "MISSING VALUE") {
inputVal.style.backgroundColor = "green";
}
}
}
checkFilled();
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
table.first{
display: table;
table-layout: auto;
float:none
margin-left: auto;
margin-right: auto;
}
.table_element{
display: table-cell;
}
</style>
</head>
<body>
<table class="first">
<div class="table_element">
<p style="text-align: center;">First Name:<br>
<input name="import_date_visit" id="subEmail" type="text" required size="25" onchange="checkFilled();" value="Claudio" />
</p>
</div>
<div class="table_element">
<p style="text-align: center;">Last name:<br><input name="import_date_visit" type="text" required size="25" onchange="checkFilled();" value="MISSING VALUE" /></p>
</div>
</table>
</body>
</html>
Firstly, you should always have a body element. Whenever you create anew HTML document, you should first paste in the following:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
</body>
</html>
Scripts and stylesheets should go into the head section, and any content that should be visible to the user in to the body section. <meta charset="utf-8"> should be always present - else non-ASCII characters will not be rendered correctly. Change utf-8 to whatever encoding you use in your editor.
Secondly, inputVal[i].value tries to access the value property of the p element in side .table_element - but paragraphs don't have a value, so you get undefined.
Thirdly, document.write and document.writeln should not be used - if you want to show something to the user, write it into a HTML element, and if you want to print something for debugging purposes, use console.log(...).
Lastly, div's are not valid children of a table - only thead, tbody and tr are.
To find the input elements, you can use document.querySelectorAll. Following the working, modern code:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style type="text/css">
table.first {
display: table;
table-layout: auto;
float: none;
margin-left: auto;
margin-right: auto;
}
.table_element {
display: table-cell;
}
</style>
<script type="text/javascript">
function checkFilled() {
let inputElements = document.querySelectorAll(".table_element input");
let outputElement = document.querySelector("#output");
outputElement.innerHTML = "You entered : ";
for (let [index, inputElement] of inputElements.entries()) {
outputElement.innerHTML += " " + (index + 1) + " " + inputElement.value;
if (inputElement.value == "") {
inputElement.style = "background-color: red;";
} else {
inputElement.style = "background-color: green;";
}
}
}
window.addEventListener("load", checkFilled);
</script>
</head>
<body>
<div class="table_element">
<p style="text-align: center;">First Name :</p>
<input name="import_date_visit" id="subEmail" type="text" required size="25" oninput="checkFilled();" value="Claudio">
</div>
<div class="table_element">
<p style="text-align: center;">Last name :</p>
<input name="import_date_visit" type="text" required size="25" oninput="checkFilled();" value="MISSING VALUE">
</div>
<p id="output">You entered : nothing yet</p>
</body>
</html>
Hi there fellow programmers!
I Want to be able to type in to the boxes how much px i want my div to move. But it won't move and I cant see whats wrong with my code. Can someone with fresh eyes spot the problem?
Any help is much appreciated!
Here's the code so far:
<!DOCTYPE html>
<html lang="sv">
<head>
<meta charset="utf-8">
<title> javascript</title>
<style>
#changeme {
background-color: lightblue;
position: absolute;
}
</style>
<script>
var $Rob = {};
$Rob.moveUpp = 0;
$Rob.moveLeft = 0;
$Rob.elementid = "";
$Rob.move = function(elementid, movex, movey)
{
$Rob.moveUpp = movey;
$Rob.moveLeft = movex;
$Rob.elementid = elementid;
$Rob.movesoft();
}
$Rob.movesoft = function() {
var elem = document.getElementById($Rob.elementid);
if ($Rob.moveUpp > 0) {
elem.style.top = (parseInt(elem.style.top) + 1) +
"px";
$Rob.moveUpp--;
} else if ($Rob.moveUpp < 0) {
elem.style.top = (parseInt(elem.style.top) - 1) +
"px";
$Rob.moveUpp++;
}
if ($Rob.moveUpp != 0) {
setTimeout($Rob.movesoft, 100);
}
}
</script>
</head>
<body>
<h1> Dynamic changes </h1>
<form>
<p>Move right:</p> <input value="0" type="text" id="moveRight" />
<p>Move down: </p> <input value="0" type="text" id="moveDown" />
<input type="button" value="Move" onClick="$Rob.move(document.getElementById('changeme'),parseInt(document.getElementById('moveRight').value),parseInt(document.getElementById('moveDown').value));" />
</form>
<div id="changeme" style="top: 100px;left: 100px;"> Hello </div>
</body>
</html>
All the best
I love Stackoverflow and its members!
cheers
// Mcgayjver
You're doing:
$Rob.move(document.getElementById('changeme'), x, y).
When you should just be doing:
$Rob.move('changeme, x, y)
Because $Rob.move expects an elementID string as a first parameter, not an actual HTMLElement.
I'm really new to working with jQuery and JSON, but I'm doing a simple weather retrieving practice project. I have got it to work except that I have to hit the Get Weather button twice in order for the Fahrenheit/Celsius button to work. I'm sure it is something small that I'm missing.
Here is all the code:
<!DOCTYPE html>
<html>
<head>
<title>Weather</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
function gettingJSON(data){
var temp = data.main.temp;
var tempC = (temp - 32) * .5556;
var far = $(".temp").html("The temperature is " + Math.floor(temp) + "F");
var cel = $(".tempC").html("The temperature in C is " + Math.floor(tempC));
cel.hide();
far.show();
$(document).on("click", "#change", function(){
far.toggle();
cel.toggle();
});
}
$(document).ready(function(){
$(document).on("click", "#getIt", function(){
var location = $(".loc").val();
var state = $(".state").val();
var apiKey = "a6253b99c39a496597483fbf2ff308ff";
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+","+state+"&units=imperial&appid=" + apiKey;
$.getJSON(url, gettingJSON);
});
});
</script>
<style>
body,html{
width: 100%;
height: 100%;
background: honeydew;
}
.temp, .tempC{
font-size: 30px;
}
</style>
</head>
<body>
<div class="toggleMe">
<p class="temp"></p>
<p class="tempC"></p>
</div>
<input type="text" class="loc" placeholder="City">
<input type="text" class="state" placeholder="State">
<button id ="getIt"> Get Weather</button>
<button id="change">C/F</button>
</body>
</html>
I'd appreciate any help available!
Thanks!
You should move the $(document).on("click", "#change", out of the gettingJSON function, otherwise - every time you call the gettingJSON function - you attache a new event listener for the click event on the #change element.
Here is your updated code:
var far = $(".temp");
var cel = $(".tempC")
function gettingJSON(data){
var temp = data.main.temp;
var tempC = (temp - 32) * .5556;
far.html("The temperature is " + Math.floor(temp) + "F");
cel.html("The temperature in C is " + Math.floor(tempC));
cel.hide();
far.show();
}
$(document).ready(function(){
$(document).on("click", "#change", function(){
far.toggle();
cel.toggle();
});
$(document).on("click", "#getIt", function(){
var location = $(".loc").val();
var state = $(".state").val();
var apiKey = "a6253b99c39a496597483fbf2ff308ff";
var url = "http://api.openweathermap.org/data/2.5/weather?q="+location+","+state+"&units=imperial&appid=" + apiKey;
$.getJSON(url, gettingJSON);
});
});
body,html{
width: 100%;
height: 100%;
background: honeydew;
}
.temp, .tempC{
font-size: 30px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div class="toggleMe">
<p class="temp"></p>
<p class="tempC"></p>
</div>
<input type="text" class="loc" placeholder="City">
<input type="text" class="state" placeholder="State">
<button id ="getIt"> Get Weather</button>
<button id="change">C/F</button>
Dekel's answer is the way to go! Additionally if you want to make it a little bit nicer you could hide the change button until the values are actually available.
To reach that set the button to be hidden by the loading of the page via CSS:
#change {
display:none;
}
and in your gettingJSON() you can then call
$('#change').show();
for displaying the button.
This is the code:
<!DOCTYPE html>
<style>
h1 {
color: white;
}
body {
background-color: black;
}
.scroller {
background: linear-gradient(#94ff98, green);
}
</style>
<html lang="en">
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h1 align="center">Fetching data...</h1>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<meter id="prog" value="0" max="100" style="width: 100%"></meter>
<script>
setInterval(
function () {
var prog = document.getElementById("prog");
var i = 0;
i = i + 1;
prog.setAttribute("value", i)
},
10
);
</script>
</body>
</html>
Yes, I know the meter element isn't for progress bars, but im just using it merely for aesthetics and it isn't doing anything at all, really.
So why is it not updating, setinterval only runs once?
The variable declaration of i should be moved outside of the setInterval callback. The variable i is reinitialize to zero for each interval.
Also, it's better to clear the interval after i has reached 100.
Demo
var i = 0;
var interval = setInterval(function() {
var prog = document.getElementById("prog");
i = i + 1;
prog.value = i;
console.log(i);
if (i >= 100) {
clearInterval(interval);
}
}, 10);
h1 {
color: white;
}
body {
background-color: black;
}
.scroller {
background: linear-gradient(#94ff98, green);
}
<h1 align="center">Fetching data...</h1>
<br>
<br>
<meter id="prog" value="10" max="100" style="width: 100%"></meter>
Try this code It will help you
<script>
var i = 0;
var interval = setInterval(function () {
var prog = document.getElementById("prog");
i = i + 1;
prog.value = i;
console.log(i);
if (i >= 100) {
clearInterval(interval);
}
}, 35);
</script>
Your code is saying: every 10 milliseconds,
access the DOM,
1 declare a variable, assign it's value to 0,
add 1 to i (0 + 1 = 1)
then set the value of your DOM element to i (e.g 1)
The problem is that your code keeps creating a new locally scoped variable i and setting it to zero each time that function is called.
You need to move i outside the scope of your anonymous function.
My code atm looks like this:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
}
init();
</script>
</body>
</html>
So what I want, is for the remove-button to remove the divs that im creating. Ive been googling around and have tried alot of different codes, cant seem to get it to work..
In your specific situation, you have two basic choices:
Just set innerHTML on the element to "":
myFigures.innerHTML = "";
It's slower than some alternatives, but you're not doing this in a tight loop, and it's easy.
Use a loop with removeChild:
while (myFigures.firstChild) {
myFigures.removeChild(myFigures.firstChild);
}
See this other SO answer for information comparing the two techniques.
Here's that first option in context:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Oppgave 2</title>
<style type="text/css">
div{
width: 100px;
height: 100px;
background-color: rgb(100, 100, 100);
margin: 5px;
float: left;
}
</style>
</head>
<body>
<label>
<ul>
<li>Antall <input id="numberFigInput" type="text"></li>
</ul>
</label>
<input id="genFigBtn" type="button" value="Generate">
<input id="removeFigBtn" type="button" value="Remove All">
<section id="myFigures"></section>
<script>
var numberFig, genFigBtn, myFigures;
function init(){
numberFigInput = document.getElementById("numberFigInput");
myFigures = document.getElementById("myFigures");
genFigBtn = document.getElementById("genFigBtn");
removeFigBtn = document.getElementById("removeFigBtn");
genFigBtn.onclick = genFigures;
removeFigBtn.onclick = removeFigures;
}
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
function removeFigures(){
myFigures.innerHTML = "";
}
init();
</script>
</body>
</html>
Like T.J. Crowder said,
myFigures.innerHTML = "";
would work. However, that assumes that myFigures is empty when your DOM is initially loaded. If that is NOT the case, you need to add a class to the div when you create it.
AddDiv function:
function genFigures(){
var numberFig = numberFigInput.value;
if (numberFig > 0, numberFig < 1001){
for(var amount = 0; amount < numberFig; amount++){
myFigures.innerHTML += "<div class='AddedDiv'></div>"
}
}else{
alert("You have to input an integer over 0, but not over 1000!");
}
}
To remove them:
$(".AddedDiv").each(function(){
$(this).parentNode.removeChild($(this));
});