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>
Related
function check_email() {
var at_present = false;
var email = document.getElementById("email").value;
if (email !== "") {
for (let i = 0; i <= email.length; i++) {
if (email[i] === "#") {
at_present = true;
break;
}
}
if (at_present == false) {
alert("Invalid email! # missing");
}
}
}
h1 {
text-align: center;
}
.background {
background-image: url("https://firebasestorage.googleapis.com/v0/b/diffusion-library.appspot.com/o/soldiers-at-a-distance-fighting-in-a-savana-biome-high-quality-little-blurred%2F1.jpg?alt=media&token=559b6e72-c738-4b56-889c-d4ad6466548d");
background-size: 1600px;
position: center;
background-position-y: -300px;
filter: blur(8px);
}
<!DOCTYPE html>
<html>
<head>
<title>MODULO ISCRIZIONE SOFTAIR</title>
<link rel="stylesheet" href="Modulo_softair_css.css">
</head>
<body>
<div class="background"></div>
<h1>MODULO ISCRIZIONE SOFTAIR</h1>
<div class="content">
<strong>Nome:</strong>
<br>
<input type="text" id="nome">
<br>
<br>
<strong>Numero di Telefono:</strong>
<br>
<input type="text" id="telefono">
<br>
<br>
<strong>Email:</strong>
<br>
<input type="text" id="email" onchange="check_email()">
</div>
<script>
</script>
</body>
</html>
The background isn't loading I don't know why. Before adding the div and class the background was loading correctly. Can somebody help me figure out why? This program is meant to be a web page for a form about softair, and I wanted to add a photo to the background with a blurred effected so that it wouldn't disturb. As I said before, I had the background in the body without the div, but when I tried to blur, it blurred the whole body. So i made the class but now it isn't working.
Thanks
Tried removing some adjectives form the css but I had no luck.
Ok so it does add, but not right
So my vars think that they are text but I want just the nums, so I can add them together.
How do I do this?
a fiddle to see whats so wrong
<html>
<head>
<title>Nose Clicker</title>
<style>
body{
background-image:url("https://i.pinimg.com/originals/66/27/70/6627703d20110ad2e8877fab5fc102b9.jpg");
}
#root-SuperGloabalVar1{
color: red;
font-size: 150px;
padding: 0px;
}
#var-wrapper{
opacity: 0%;
}
</style>
</head>
<body>
<div id = 'var-wrapper'>
<h1 class = 'vars' id = 'perclick'>
<---here is the first addend--->
1
</h1>
</div>
<---here the second one--->
<h1 id = 'root-SuperGloabalVar1'>0</h1>
<img onclick = '
<---get number 1--->
var v = getElementById("root-SuperGloabalVar1");
<---get number 2--->
var a = getElementById("perclick");
<---adding--->
var w = v.innerHTML+=a.innerHTML;
<---replacing and then it shows "01"--->
v.innerHTML(parrseint(a.innerHTML + v));
'
src = 'https://www.pngitem.com/pimgs/m/155-1559954_cartoon-nose-images-cartoon-nose- image-png-transparent.png'>
</body>
</html>
I didn't completely understand your question can you explain it a bit more and detailed but if you want to parse text into number then use
var x = a.innerHTML;
Number(x)
Edit:
And a proper way to use number increment and display it is like this:
(you don't need to save your integer in an element you can use a javascript variable)
let clicks = 0;
function countClicks() {
clicks++;
const display = document.getElementById("display");
display.innerHTML = clicks;
}
<!DOCTYPE html>
<html lang="en">
<body>
<div style="background: red; width: 100px; height: 100px;" onclick="countClicks();">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>
</html>
Example to use in onclick callback:
<body>
<script>var clicks = 0;</script>
<div style="background: red; width: 100px; height: 100px;"
onclick=
"
clicks++;
const display = document.getElementById('display');
display.innerHTML = clicks;
">
</div>
<div style="font-size: 30px;" id="display">0</div>
</body>
To start off I'm terrible at Js and super new at it. I'm trying to make a random image pop up when the site goes to a 404. I can't tell if my website is actually running the code or not because console.log wasn't working. Because of that I took all my CSS and js and put it all into the same HTML file to see if that was the problem (it wasn't) Any help is much appreciated :)
HTML:
<html>
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<div id="getMeme()"></div>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
</body>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
document.getElementById("result").onload = '<img src="' + meme[pp] + '" />';
}
</script>
</html>
Using your code, you would need to ensure the function getMeme is called/invoked. Furthermore, you would need to update the function to modify the innerHTML of the element with id result instead of assigning to it's event handler onload.
See demo below:
I've included a console.log for debugging purposes on stackoverflow as images shared in the question are not available.
<head>
<?php include $_SERVER["DOCUMENT_ROOT"]."/php/ballsdeep1headndnav.php"; ?>
<link rel="stylesheet" href="../main.css" />
<style>
.yikes {
background-color: black;
}
.white {
color: white;
}
.cute_block {
border: blue;
border: 10px;
margin: 50px;
}
label {
margin: 10px;
}
input {
margin: 10px;
color: black;
}
</style>
<title>Yikes.</title>
</head>
<body class="yikes">
<h1 class="center white">
<404>
</h1>
<span id="result"></span>
<p class="white cute_block center">We have no clue how you ended up here</p>
<form class="white cute_block center">
<label for="how">How did you get here</label>
<input type="text" id="how" name="how"><br><br>
<label for="else">Anything else?</label>
<input type="text" id="else" name="else"><br><br>
<input type="submit" value="Submit">
</form>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-p34f1UUtsS3wqzfto5wAAmdvj+osOnFyQFpp4Ua3gs/ZVWx6oOypYoCJhGGScy+8" crossorigin="anonymous"></script>
<script>
function getMeme() {
var meme = new Array('images/no_more-ico.png', 'images/nothing.png', 'images/phpfiles.png', 'images/sike.png');
var pp = Math.floor(Math.random() * meme.length);
console.log("chose meme",meme[pp]); //line included for debugging purposes on stackoverflow as images shared in question are not available
//update `innerHTML` of target element
document.getElementById("result").innerHTML = '<img src="' + meme[pp] + '" />';
}
//call function to getMeme at the end of the page
getMeme();
</script>
</body>
</html>
I am a beginner at JavaScript and I have been working on this very simple project for a couple of days. It is supposed to allow you to calculate the area and perimeter of a rectangle, but despite how much I tweaked the code, it will not calculate when I enter numbers. It should just be a simple user interface that allows you to input into two text boxes:
var $ = function (id) {
return document.getElementById(id);
}
var calculate_click = function () {
var width = parseFloat($("width").value);
var length = parseFloat($("length").value);
$("area").value = "";
$("perimeter").value = "";
if (isNaN(width) || width <= 0) {
alert("Width must be a valid number and greater than zero.");
}
else if (isNaN(length) || width <= 0) {
alert("Length must be a valid number and greater than zero.");
} else {
var area = width * length;
var perimeter = 2 * width + 2 * length;
$("area").value = area;
$("perimeter").value = perimeter;
}
window.onload = function () {
$("calculate").onclick = calculate_click;
$("length").focus();
}
}
body {
font-family: Arial, Helvetica, sans-serif;
background: #333366; }
#content {
width: 450px;
margin: 10px auto;
padding: 5px 20px;
background: white;
border: thin solid black; }
#salesTax, #total {
color: black; }
#taxCalc label {
display: block;
width: 6em;
text-align: right;
padding-right: 1em;
float: left; }
#taxCalc input {
display: block;
float: left; }
#taxCalc br {
clear: left; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Area and Perimeter Calculator</title>
<link rel="stylesheet" type="text/css" href="sales_tax.css" />
<script type="text/javascript" src="sales_tax.js"></script>
</head>
<body>
<div id="content">
<h2>Area and Perimeter Calculator</h2>
<p>Enter the values below and click "Calculate".</p>
<div id="taxCalc">
<label for="length">Length:</label>
<input type="text" id="length" /><br />
<label for="width">Width:</label>
<input type="text" id="width" /><br />
<label for="area">Area:</label>
<input type="text" id="area" disabled="disabled" /><br />
<label for="perimeter">Perimeter:</label>
<input type="text" id="total" disabled="disabled" /><br />
<label> </label>
<input type="button" id="calculate" value="Calculate" /><br />
</div>
</div>
</body>
</html>
If anyone can please help even a little, I would genuinely appreciate it,
Thank you.
There were two problems with your script (Well technically three, but I think the missing v at the beginning was a copy/paste mistake.
1st: The window.onload functions needs to be outside calculate_click. It never gets called, because the calculate_click never gets called.
2nd: The input for perimeter, had id="total", but you were calling $("perimeter"). This is fixed in the jsfiddle.
Here is a working form.
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));
});