Trying to add background to <td> when clicked - javascript

A quick overview of what I'm trying to do: I created a function that takes user input of rows and columns and creates a grid. Then i want the user to pick a color and click on any pixel of the grid and apply the color. The table function works but my adding color function is not. Need a guide please
My Html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Pixel Art Maker!</title>
<link
rel="stylesheet"
href="https://fonts.googleapis.com/css?family=Monoton"
/>
<link rel="stylesheet" href="css/styles.css" />
</head>
<body>
<h1>Lab: Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
<form id="sizePicker">
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1" />
Grid Width:
<input type="number" id="inputWidth" name="width" min="1" value="1" />
<input type="submit" />
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker" />
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="js/mine.js"></script>
</body>
</html>
my Javascript:
function makeGrid() {
let table = document.querySelector("#pixelCanvas");
let rows = document.querySelector("#inputHeight").value;
let cols = document.querySelector("#inputWidth").value;
let fulltable = "";
for (i = 0; i < rows; i++) {
fulltable += "<tr>";
for (y = 0; y < cols; y++) {
fulltable += "<td></td>";
}
fulltable += "</tr>";
}
table.innerHTML = fulltable;
return false;
}
function addColor() {
var cells = document.querySelectorAll("td");
cells.forEach((td) => {
td.onclick = () => {
let userColor = document.querySelector("#colorPicker").value;
this.style.backgroundColor = userColor;
};
});
}
document.addEventListener("DOMContentLoaded", () => {
addColor();
document.querySelector("#sizePicker").onsubmit = makeGrid;
});

Related

JS local storage button coding

hey i need help with creating a delete button for my "notes" so it will delete it from the screen and the localstorage (u will notice i tried to make a delBtn function but with no success) i would appreciate if someone could post a fix to mine and explain me where i went wrong.
My JS
const tableBody = document.getElementById("tableBody");
const taskInfo = document.getElementById("taskInfo");
const taskDate = document.getElementById("taskDate");
const taskTime = document.getElementById("taskTime");
const delBtn = document.getElementById("delBtn")
let x = new Task("this is a test", "2021-04-14", "03:19");
let y = new Task("this is a 2nd test", "2021-04-14", "03:19");
//x.add();
//y.add();
let taskList = [
x, y, (new Task("this is a 3rd test", "2021-04-14", "03:19"))
];
if (localStorage.savedTaskList)
taskList = JSON.parse(localStorage.savedTaskList);
displayTable();
function displayTable() {
tableBody.innerHTML = "";
for (let task of taskList) {
const div = document.createElement("div");
div.setAttribute("class","taskZone");
const divTaskInfo = document.createElement("div");
divTaskInfo.setAttribute("class","taskInfo");
const divTaskDate = document.createElement("div");
divTaskDate.setAttribute("class","taskDate");
const divTaskTime = document.createElement("div");
divTaskTime.setAttribute("class","taskTime");
const delBtn = document.createElement("span");
delBtn.setAttribute("class","delBtn");
divTaskInfo.innerText = task.taskInfo;
divTaskDate.innerText = task.taskDate;
divTaskTime.innerText = task.taskTime;
div.append(divTaskInfo, divTaskDate, divTaskTime);
tableBody.appendChild(div);
}
}
delBtn.onclick = function delTask() {
delBtn.parentNode.removeChild(taskZoneElmToDel)
}
function addTask() {
if (taskInfo.value == '' || taskDate.value == '' || taskTime.value == '') {
return alert(`Please fill all the fields.`);
}else{newTask = new Task(taskInfo.value, taskDate.value, taskTime.value);
taskList.push(newTask);
localStorage.savedTaskList = JSON.stringify(taskList);
displayTable();
}
}
Thats the Html part of it
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Task Board</title>
<link rel="stylesheet" href="style.css">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
</head>
<body>
<div class="scaleable-wrapper" id="scaleable-wrapper">
<div class="very-specific-design" id="very-specific-design">
<header class="Title">
My Task Board
</header>
<div id="Input">
</br>
</br>
<form class="Form" id="formInfo">
<label for="taskInfo">Task Info:</label>
<input type="text" id="taskInfo" name="taskInfo" required autofocus></input></br>
<label for="taskDate">Task Date:</label>
<input type="date" id="taskDate" name="taskDate" required></input></br>
<label for="taskTime">Task Time:</label>
<input type="time" id="taskTime" name="taskTime" required></input></br>
<input type="submit" id="addTaskDiv" class="btn" value="Save" onclick="addTask()"></input>
<input type="reset" id="resetForm" class="btn"></input>
</form>
</br>
</br>
</div>
<div class="outNotes"></div>
<div class="tableBody">
<table>
<tbody id="tableBody">
</tbody>
</table>
</div>
</div>
</div>
<input type="button" id="delBtn">x</input>
</body>
<script src="Task.js"></script>
<script src="script2.js"></script>
</html>

JS and onchange event in html form

My code error is pretty obvious but I canĀ“t see it.
It's very simple my form ask the height and weight and calculate the corporal mass index the user input height in meters and convert to inches (function works ok)
input kilos and convert to pounds (works ok too) but in this process must calculate the index and write it in another textbox. that's my problem!
What am I doing wrong??? heres my code:
function myFunctionmts() {
var x = document.getElementById("mters");
var y = document.getElementById("inches");
y.value = ((x.value*100)/2.54).toFixed(2);
document.getElementById("mters").value=x.value;
document.getElementById("inches").value=y.value;
}
</script>
<script>
function myFunctionkg() {
var i = document.getElementById("imc");
var p = document.getElementById("inches");
var x = document.getElementById("kilos");
var z = document.getElementById("pounds");
var step1 = 0;
var step2 = 0;
var step3 = 0;
z.value = (x.value/.454).toFixed(2);
libras.value=z.value;
document.getElementById("pounds").value=z.value;
step1.value = z.value*703;
step2.value = step1.value/p.value;
step3.value = (step2.value/p.value).toFixed(1);
document.getElementById("imc").value=step3.value
}
<form method="POST" action="#">
<input type="text" name="mters" id="mters" required onchange="myFunctionmts()">
<input type="text" name="inches" id="inches" placeholder="Inches" readonly>
<input type="text" name="kilos" id="kilos" required onchange="myFunctionkg()">
<input type="text" name="pounds" id="pounds" placeholder="Pounds" readonly>
<input type="text" name="imc" id="imc" readonly>
<input type="submit" value="Save">
</form>
Try to use this code:
HTML :
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Stack Overflow</title>
<link
rel="stylesheet"
href="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css"
/>
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<!-- Popper JS -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.4.1/js/bootstrap.min.js"></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<form method="POST" action="#">
<label for="mters">meter</label>
<input
type="text"
name="mters"
id="mters"
required
onchange="myFunctionmts()"
/>
<label for="inches">inches</label>
<input
type="text"
name="inches"
id="inches"
placeholder="Inches"
readonly
/>
<label for="kilos">kilos</label>
<input
type="text"
name="kilos"
id="kilos"
required
onchange="myFunctionkg()"
/>
<label for="pounds">pounds</label>
<input
type="text"
name="pounds"
id="pounds"
placeholder="Pounds"
readonly
/>
<label for="imc">imc</label>
<input type="text" name="imc" id="imc" readonly />
<input type="submit" value="Save" />
</form>
<script src="script.js"></script>
</body>
</html>
JS:
function myFunctionmts() {
var x = document.getElementById('mters');
var y = document.getElementById('inches');
y.value = ((x.value * 100) / 2.54).toFixed(2);
document.getElementById('mters').value = x.value;
document.getElementById('inches').value = y.value;
}
function myFunctionkg() {
var imc = document.getElementById('imc'); // mass index
var inches = document.getElementById('inches'); //
var kilos = document.getElementById('kilos');
var pounds = document.getElementById('pounds'); // pounds
var step1 = 0;
var step2 = 0;
var step3 = 0;
pounds.value = (+kilos.value / 0.454).toFixed(2);
// undefined error here, what is this libras all about ???
// libras.value = z.value;
step1 = +pounds.value * 703;
step2 = +step1 / +inches.value;
step3 = (+step2 / +inches.value).toFixed(1);
console.log(step3);
imc.value = step3;
}
Hope it helps.

When I click the Calculate button, it does not display the calculations in textbox for sales tax and total

When I run the code on my chrome browser, clicking the calculate button, it does not put the value in the Total and Sales Tax text box.
Also "Add the Javascript event handler for the click event of the Clear button, This should clear all text boxes and move the cursor to the Subtotal field."
I'm using Html and js file. Using a function expression to calculate and display my calculation, then also use the clear button to clear all text boxes.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>
This is my js file.
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.
")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = sumSalesTax;
};
Sales Tax Calculator
It seems like you had a typo when you were doing $("clear").onclick = sumSalesTax;, as the variable was named SumSalesTax rather than with the lower case. This meant that the code block errored out and therefore didn't actually run. Make sure you make good use of the browser console so you can spot errors like this! The below example should work
var $ = function (id) {
return document.getElementById(id);
};
var SumSalesTax = function (sub, rate){
var sales_tax = (sub * rate);
sales_tax = sales_tax.toFixed(2);
var total = (sub * rate + sub);
total = total.toFixed(2);
return sales_tax, total;
}
var processEntries = function() {
var sub = parseFloat($("subtotal").value);
var rate = parseFloat($("tax_rate").value);
if (sub < 0 && sub > 10000 && rate < 0 && rate > 12) {
alert("Subtotal must be > 0 and < 1000, and Tax Rate must be >0 and < 12.")
} else {
$("sales_tax").value = SumSalesTax(sub, rate);
$("total").value = SumSalesTax(sub, rate);
}
};
window.onload = function() {
$("calculate").onclick = processEntries;
$("clear").onclick = SumSalesTax;
};
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Sales Tax Calculator</title>
<link rel="stylesheet" href="styles.css" />
<script src="sales_tax.js"></script>
</head>
<body>
<main>
<h1>Sales Tax Calculator</h1>
<p>Enter Subtotal and Tax Rate and click "Calculate".</p>
<label for="subtotal">Subtotal:</label>
<input type="text" id="subtotal" ><br>
<label for="tax_rate">Tax Rate:</label>
<input type="text" id="tax_rate" ><br>
<label for="sales_tax">Sales Tax:</label>
<input type="text" id="sales_tax" disabled ><br>
<label for="total">Total:</label>
<input type="text" id="total" disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calculate" >
<input type="button" id="clear" value="Clear" ><br>
</main>
</body>
</html>

Jquery & HTML - dynamically create div-table

Say I have a textfield where the dimensions of the table are given. like 2 3
now I need to write a function that creates a table out of div-tags with those dimensions. The table has to be inserted in the <div id="output"> -element
I was thinking of making a string with osme for-loops that looks like this
<div>
<div> </div>
<div> </div>
</div>
<div>
... (more columns)
</div>
So that looks like a sequence of div-tags and afterwards I would convert this to html and insert it.
But isn't there a more efficient way?
In your Javascript,
<script type="text/javascript">
var rows,cols,str="";
function generateTable()
{
rows = documnt.getElementById('rows').value;
cols = documnt.getElementById('cols').value;
str ="<table>"
for(var i=0;i<rows;i++)
{
str = str+"<tr>";
for(vat j=0;j<cols;j++)
{
str = str+"<td></td>";
}
str =str+"</tr>";
}
str = str + "</table>;
documnt.getElementById('output').innerHTML = str;
}
</script>
In your HTML,
<input type="number" id="rows" placeholder="Number of rows" />
<input type="number" id="cols" placeholder="Number of cols" />
<input type="button" id="submit" value="Submit" onClick="generateTable();" />
<br>
<br>
<div id="output"></div>
Something like this maybe:
var rows = 3; //these would be populated by your text field entries
var columns = 2;
function makeTable() {
html = '<table>';
for(var i=0; i<rows; i++) {
html += '<tr>';
for(var j=0; j<columns; j++) {
html += '<td><p>Some Data</p></td>';
}
html += '</tr>';
}
html += '</table>';
document.getElementById("output").innerHTML = html;
}
table, td {
border: 1px solid black; padding: 5px;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Table Maker</title>
</head>
<body>
<div id="output" onClick="makeTable()"><h1>Click me to make a table!</h1></div>
</body>
</html>

how to display different function in a same textbox?

I have this html code with javascript. My average value displays correctly but my find minimum is not displaying anything. Its supposed to show when the user clicks on the find min button on the box.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var calculateGrade = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) ) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("average").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3=parseFloat($("exam3").value);
if ( (exam1<exam2) && (exam1<exam3)){
$("mini").value=exam1;}
else if ((exam2<exam1) && (exam2<exam3)){
$("mini").value=exam2;}
else {
$("mini").value=exam3;
}
}
window.onload = function () {
$("calculate").onclick = calculateGrade;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate Average</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="average"disabled ><br>
<label> </label>
<input type="button" id="calculate" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Calculate Your Grade</title>
<link rel="stylesheet" href="calc.css">
<script>
var $ = function (id) {
return document.getElementById(id);
}
var average = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
}
else {
var average = (exam1 + exam2 + exam3) / 3;
$("result").value = average;
}
}
var min = function () {
var exam1 = parseFloat($("exam1").value);
var exam2 = parseFloat($("exam2").value);
var exam3 = parseFloat($("exam3").value);
if (isNaN(exam1) || isNaN(exam2) || isNaN(exam3)) {
alert("All three entries must be numeric");
} else {
$("result").value = Math.min(exam1,exam2,exam3);
}
}
window.onload = function () {
$("average").onclick = average;
$("mini").onclick = min;
$("exam1").focus();
}
</script>
</head>
<body>
<section>
<h1>Calculate</h1>
<label for="exam1">Exam1:</label>
<input type="text" id="exam1"><br>
<label for="exam2">Exam2:</label>
<input type="text" id="exam2"><br>
<label for="exam3">Exam3:</label>
<input type="text" id="exam3"><br>
<label for="average"></label>
<input type="text" id="result" disabled ><br>
<label> </label>
<input type="button" id="average" value="Calc Avg">
<input type="button" id="mini" value="Find min">
</section>
</body>
</html>
The issue is with the min function. Instead of setting the value of textbox (probably, missing in your code example) you are setting the value of button "mini" (which is incorrect).
Update:
You need to be including one more textbox <input type="text" id="txtMin" disabled ><br>
and update your min function to set the value of it, as follows:
$("txtMin").value=exam1;
...
$("txtMin").value=exam2;
...
$("txtMin").value=exam3;

Categories