I have tried to generate the rows using javascript, but i'm learning jquery and I wish to use it to implement this functionality.
HTML
<form id="sizePicker">
Grid Height:
<input type="number" id="input_height" name="height" min="1" value="1">
Grid Width:
<input type="number" id="input_width" name="width" min="1" value="1">
<input type="submit">
</form>
<table id="pixel_canvas"></table>
JAVASCRIPT/JQUERY
function makeGrid() {
var table = document.getElementById("pixel_canvas");
//var table = $('#pixel_canvas');
table.innerHTML = "";
while($('#pixel_canvas tr').length > 0)
table.deleteRow(0);
var inputHeight = $('#input_height').val();
var inputWidth = $('#input_width').val();
for(var i = 0; i < inputHeight; i++){
var row = table.insertRow(i);
for(var j = 0; j < inputWidth; j++){
var cell = row.insertCell(j);
}
}
return false;
}
sizePicker.submit(function(evt){
evt.preventDefault();
makeGrid();
});
Here, the table DOM methods such as insertRow() and insertCell() is inactive if I implement the same methods using jquery.
var table = $('#pixel_canvas');
var row = table.insertRow(i); // The browser responses not a function
insertRow is Javascript DOM function. So, with JQuery you have to fetch the DOM element and not the jquery object. Use $('#pixel_canvas').get(0) to fetch the DOM element.
function makeGrid() {
var table = $('#pixel_canvas').get(0);
table.innerHTML = "";
while($('#pixel_canvas tr').length > 0)
table.deleteRow(0);
var inputHeight = $('#input_height').val();
var inputWidth = $('#input_width').val();
for(var i = 0; i < inputHeight; i++){
var row = table.insertRow(i);
for(var j = 0; j < inputWidth; j++){
var cell = row.insertCell(j);
}
}
return false;
}
$('#sizePicker').submit(function(evt){
evt.preventDefault();
makeGrid();
});
table, th, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="sizePicker">
Grid Height:
<input type="number" id="input_height" name="height" min="1" value="1">
Grid Width:
<input type="number" id="input_width" name="width" min="1" value="1">
<input type="submit">
</form>
<table id="pixel_canvas"></table>
Related
Given two input fields, I would like to create a grid that takes the first input as the rows, and second input as the columns, and appears once a separate button is clicked.
I know how to make a grid NxN, but I want a grid NxY, that specifically gets created via a button.
const grid = document.querySelector("#gridDiv");
const rowSize = document.querySelector("#rowInput");
const colSize = document.querySelector("columnInput");
const button = document.querySelector("button");
function NxY(n, y) {
let rowsArr = [];
let columnArr = [];
for (let i = 0; i < n; i++) {
columnArr.push(i);
}
for (let i = 0; i < y; i++) {
rowsArr.push(columnArr);
}
render(rowsArr)
}
function render(arr) {
arr.forEach((items) => {
let outerDiv = document.createElement("div")
outerDiv.classList.add("row");
items.forEach((item) => {
let dv = document.createElement("div");
dv.classList.add("cell");
outerDiv.appendChild(dv);
});
grid.appendChild(outerDiv);
});
}
NxY(3, 4);
This will automatically produce the grid specified at the bottom, but my issue is figuring out how to add an eventListener to the button that will correctly guide it to creating the proper grid.
Try this snippet
$('#btnInsert').click(function(){
$('#mtable tbody').html('');
var row_count = $('#row').val();
var col_count = $('#col').val();
if(row_count && col_count){
//entry is valid
while(row_count > 0){
//add new row
$('#mtable tbody').append($("<tr>"));
row_count--;
}
while(col_count > 0){
//add new column
$('#mtable tr').append($("<td>"));
$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
col_count--;
}
}else{alert('Invalid entry');}
});
$('#btnInsert2').click(function(){
$('#mDiv').html('');
var row_count = $('#row2').val();
var col_count = $('#col2').val();
if(row_count && col_count){
//entry is valid
while(row_count > 0){
//add new row
$('#mDiv').append($("<div class='row'>"));
row_count--;
}
while(col_count > 0){
//add new column
$('#mDiv').children('.row').each(function(){$(this).append($('<div class="col col-md-4">'))});
col_count--;
}
}else{alert('Invalid entry');}
});
td{padding:5px;}
.col{margin:5px;
min-height: 50px;
background: #aaaaaa;}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<h3>For Tables </h3>
<input id="row" type="number" max="20" placeholder="Enter no. of rows"/>
<input id="col" type="number" max="20" placeholder="Enter no. of columns"/>
<button id="btnInsert">Generate Grid</button>
<table border="1" id="mtable">
<tbody></tbody>
</table><br/><br/><br/><br/>
<h3>For Divs </h3>
<input id="row2" type="number" max="20" placeholder="Enter no. of rows"/>
<input id="col2" type="number" max="20" placeholder="Enter no. of columns"/>
<button id="btnInsert2">Generate Grid</button>
<br>
<div class="container" id="mDiv"></div><br/><br/><br/><br/>
I have a code in which the user enters the number of rows and columns. the table of given rows and columns are created with each cell has an event of onClick, where the user clicks on any cell and the background color of the cell changes. in my code how do I change the background color of the cell?
<body>
Grid Height:
<input id="n1" type="number" name="height" min="1" value="1">
Grid Width:
<input id="n2" type="number" name="width" min="1" value="1">
<input type="submit" onclick="makegrid()">
<table width="100px" height="100px" id="myTable" border="1" style="border-collapse:collapse" >
</table>
<script>
var x,rn,cn;
function makegrid()// function called after submit button is clicked
{
rn = parseInt(document.getElementById("n1").value); //fetches the entered rows by user
cn = parseInt(document.getElementById("n2").value); //fetches the entered column by user
for(var r=0;r<rn;r++)
{
x=document.getElementById("myTable").insertRow(r); //insert row to the table
for(var c=0;c<cn;c++)
{
var y= x.insertCell(c); //insert cells to each row
}
}
}
</script>
Add click listener to the document, check if the clicked element is td if yes change the background color of cell.
var x, rn, cn;
function makegrid() // function called after submit button is clicked
{
rn = parseInt(document.getElementById("n1").value); //fetches the entered rows by user
cn = parseInt(document.getElementById("n2").value); //fetches the entered column by user
for (var r = 0; r < rn; r++) {
x = document.getElementById("myTable").insertRow(r); //insert row to the table
for (var c = 0; c < cn; c++) {
var y = x.insertCell(c); //insert cells to each row
}
}
}
document.addEventListener('click', ({target}) => {
if (target.tagName == "TD") {
target.style.backgroundColor = "red";
}
});
Grid Height:
<input id="n1" type="number" name="height" min="1" value="1"> Grid Width:
<input id="n2" type="number" name="width" min="1" value="1">
<input type="submit" onclick="makegrid()">
<table width="100px" height="100px" id="myTable" border="1" style="border-collapse:collapse">
</table>
I'm trying to make something that makes it easier to write out a matrix/matrices.
You start with getting two number inputs for the dimensions of the matrix. And after that you "submit" the numbers and out comes several input boxes.
How do you write this code? Is it possible to do it in another function?
I was thinking of having the "submit" button have a validification to see if numbers are real, and if they are the function continues with for loops on how to "write" out the number boxes.
This is what I got right now:
function validate(){
var num;
num = document.getElementById("numberbox").value;
var myForm = document.getElementById('payForm'); //
while(myForm.hasChildNodes()){
myForm.removeChild(myForm.firstChild);
}
myForm = document.createElement("form");
myForm.setAttribute("method","post");
myForm.setAttribute("action","processChecking.php");
if(isNaN(num) || num<1){
document.getElementById("output").innerHTML = "invalid number!";
document.getElementById("numberbox").value = '';
} else {
document.getElementById("output").innerHTML = "number validated!";
array(num);
for (var i = 0; i <= num; i++) {
var input = document.createElement('input');
input.type = 'text';
input.name = 'myInput_' + i;
input.id = 'myInput_' + i;
myForm.appendChild(input);
}
}
}
<body>
<table>
<tr>
<td>
<p>
Enter number for how many number boxes you want:<br>
<input id="numberbox" type="number">
<button type="button" onclick="validate()">Validate</button>
<br>
<p id="output"></p>
<br>
</p>
</td>
<td style="text-align:right;">
<p id="payForm"></p>
</td>
</tr>
</table>
</body>
Here is what I made from your question so far. If it is on track, then we can build upon it.
function createTable() {
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var theader = '<table border="1">\n';
var tbody = '';
for (var i = 0; i < num_rows; i++) {
tbody += '<tr>';
for (var j = 0; j < num_cols; j++) {
tbody += '<td>';
tbody += '<input type="number">'
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
<form name="tablegen">
<label>Input number of rows :
<input type="number" name="rows" id="rows" />
</label>
<br />
<label>Input number of columns :
<input type="number" name="cols" id="cols" />
</label>
<br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();' />
</form>
<div id="wrapper"></div>
Here is a somewhat simplified version of the code I am currently using:
https://jsfiddle.net/2zauty83/8/
Javascript
function checkboxlimit(checkgroup) {
var checkgroup = checkgroup
for (var i = 0; i < checkgroup.length; i++) {
checkgroup[i].onclick = function() {
var checkedcount = 0
for (var i = 0; i < checkgroup.length; i++)
checkedcount += (checkgroup[i].checked) ? 1 : 0
if (checkedcount > 2) {
this.checked = false
}
}
}
}
var sort_form = document.forms.sortus;
var sort_checkboxes = sort_form.elements['squarepick[]'];
checkboxlimit(sort_checkboxes);
CSS
input.square {
margin: 0;
padding: 0;
display: none;
}
.sorttile {
cursor: pointer;
display: inline-block;
width: 20px;
height: 20px;
border: 2px solid #CCCCCC;
margin: 1px;
}
.sorttile:hover {
border: 2px solid #AAAAAA;
}
HTML
<form enctype='multipart/form-data' method='POST' id='sortus'>
<input id='1-1' class='square' type='checkbox' name='squarepick[]' value='1-1' />
<label class='sorttile' for='1-1' style='background-color:#FF0000;'>
<input type='hidden' name='1-1' value='#FF0000' />
</label>
<input id='1-2' class='square' type='checkbox' name='squarepick[]' value='1-2' />
<label class='sorttile' for='1-2' style='background-color:#FFFF00;'>
<input type='hidden' name='1-2' value='#FFFF00' />
</label>
<input id='1-3' class='square' type='checkbox' name='squarepick[]' value='1-3' />
<label class='sorttile' for='1-3' style='background-color:#00FF00;'>
<input type='hidden' name='1-3' value='#00FF00' />
</label>
<br/>
<input id='2-1' class='square' type='checkbox' name='squarepick[]' value='2-1' />
<label class='sorttile' for='2-1' style='background-color:#00FFFF;'>
<input type='hidden' name='2-1' value='#00FFFF' />
</label>
<input id='2-2' class='square' type='checkbox' name='squarepick[]' value='2-2' />
<label class='sorttile' for='2-2' style='background-color:#0000FF;'>
<input type='hidden' name='2-2' value='#0000FF' />
</label>
<input id='2-3' class='square' type='checkbox' name='squarepick[]' value='2-3' />
<label class='sorttile' for='2-3' style='background-color:#FF00FF;'>
<input type='hidden' name='2-3' value='#FF00FF' />
</label>
<br/>
<input id='3-1' class='square' type='checkbox' name='squarepick[]' value='3-1' />
<label class='sorttile' for='3-1' style='background-color:#000000;'>
<input type='hidden' name='3-1' value='#000000' />
</label>
<input id='3-2' class='square' type='checkbox' name='squarepick[]' value='3-2' />
<label class='sorttile' for='3-2' style='background-color:#999999;'>
<input type='hidden' name='3-2' value='#999999' />
</label>
<input id='3-3' class='square' type='checkbox' name='squarepick[]' value='3-3' />
<label class='sorttile' for='3-3' style='background-color:#FFFFFF;'>
<input type='hidden' name='3-3' value='#FFFFFF' />
</label>
</form>
Basically each colored square represents a checkbox, allowing you to select any two boxes. Additionally, each box has a hidden input field associated with it.
For simplified demonstration purposes, the demo uses "background-color", but my actual code uses "background-image".
What I would like to do is make it so that when two squares are picked, upon selecting the second box, the two boxes trade each other's "background-image" values, effectively making it appear like the two squares traded places.
In addition, however, I also need to swap the values of the hidden-type input fields.
Finally, the two checkboxes should be deselected, although that part is easy. What I'm having trouble with is the first two parts. I thought I had some idea of how to make it work, but my experiments haven't been working out (My knowledge of javascript is still fairly crude).
Any ideas on how to make this work?
The first thing you need to do is set up an event listener so you know when a box has been checked. The second thing you need to do is to keep track of what got checked. Finally, you want to perform a series of operations based on what was checked.
var formEl = document.getElementById("sortus");
// Track our checked boxes
var checked = [];
var swap = function () {
var boxA = checked[0];
var boxB = checked[1];
// Get hidden fields using checkbox ID
var hiddenA = document.getElementsByName(boxA.id)[0];
var hiddenB = document.getElementsByName(boxB.id)[0];
var boxAbackgroundImage = boxA.style.backgroundImage;
var hiddenAvalue = hiddenA.value;
// Switch images!
boxA.style.backgroundImage = boxB.style.backgroundImage;
boxB.style.backgroundImage = boxAbackgroundImage;
// Swap hidden input values
hiddenA.value = hiddenB.value;
hiddenB.value = hiddenAvalue;
};
var reset = function () {
for (var i = 0; i < checked.length; i++) {
checked[i].checked = false;
}
checked = [];
};
var isDuplicate = function (el) {
for (var i = 0; i < checked.length; i++) {
if (checked[i] === el) {
return true;
}
}
return false;
};
formEl.addEventListener("click", function (e) {
var el = e.target;
// Was it a checkbox clicked?
if (el.className == "square") {
// Is it already checked?
if (!isDuplicate(el)) {
checked.push(el);
if (checked.length === 2) {
swap();
reset();
}
}
}
});
I didn't test this code but I hope it gives you a clear sense of what you need to do.
Basic function for your above requirement can be found in the below link,
Fiddler Link
function checkboxlimit(checkgroup)
{
var checkgroup = checkgroup
for (var i = 0; i < checkgroup.length; i++) {
checkgroup[i].onclick = function()
{
var checkedcount = 0
for (var i = 0; i < checkgroup.length; i++)
checkedcount += (checkgroup[i].checked) ? 1 : 0
if (checkedcount > 2) {
this.checked = false
}
swapImage();
}
}
}
function swapImage()
{
var prevStyle="";
var prevId="";
for (var i = 0; i < sort_checkboxes.length; i++) {
if(sort_checkboxes[i].checked)
{
if(prevId!="")
{
document.getElementById(prevId).nextElementSibling.style.backgroundColor = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
document.getElementById(prevId).nextElementSibling.children[0].value = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
sort_checkboxes[i].nextElementSibling.style.backgroundColor = prevStyle;
sort_checkboxes[i].nextElementSibling.children[0].value = prevStyle;
prevStyle = "";
prevId = "";
}
else
{
prevId=sort_checkboxes[i].id;
prevStyle = sort_checkboxes[i].nextElementSibling.style.backgroundColor;
}
}
}
}
i am creating a checkout page where users can purchase goods. i have managed to give each product its price but what I cant do is give them its quantity. i simply do no know how to do it. i created a quantity box for them but i can link the two.
my goal is to update the quantity and total price should be displayed on the checkout form.
since this is my homework for college, this must be done in strictly javascript if a solution arrives.
<script type="text/javascript">
function total(frm) {
var tot = 0;
for (var i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if (frm.elements[i].checked) tot += Number(frm.elements[i].value);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
type = "text/javascript" > total(document.getElementById("theForm"));
}
</script>
<form action="nextpage" method="post" id="theForm">
<fieldset>
<legend>Choose your Products</legend>
<table style="padding:2px">
<tr>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
<td>
<img src="http://placehold.it/200x200" />
</td>
</tr>
<tr>
<td class="buttons">
<div>
<input type="checkbox" name="r" value="25" onclick="total(this.form);" />£25</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="7" value="50" onclick="total(this.form);" />£50</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="asd7" value="75" onclick="total(this.form);" />£75</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
<td class="buttons">
<div>
<input type="checkbox" name="rasd7" value="100" onclick="total(this.form);" />£100</div>
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</td>
</tr>
</table>
<div id="totalDiv">£0</div>
<div>
<input type="submit" value="Place Order" />
</div>
</fieldset>
</form>
http://jsfiddle.net/isherwood/96qkr/
Simple and fast solution
Well the simplest solution would be:
Number(frm.elements[i].value) * Number(frm.elements[i+1].value);
Since the quantity element always comes AFTER the checkbox element.
The JavaScript then becomes:
function total(frm)
{
var tot = 0;
for (var i = 0; i < frm.elements.length; i++) {
if (frm.elements[i].type == "checkbox") {
if (frm.elements[i].checked) tot +=
Number(frm.elements[i].value) * Number(frm.elements[i+1].value);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
}
You can see this works here.
To guarantee that the total div also gets updated when quantity is changed, you should add the onclick="total(this.form);" event to the class="quantity" input elements as well.
You can see how nicely this works here.
More advanced solution
Personally, I would use tabIndex to group the checkbox and quality inputs.
For example, for the first product:
<td class="buttons">
<div>
<input tabindex="1" name="checkbox" type="checkbox" value="25" onclick="total(this.form);" />£25</div>
<input tabindex="1" name="quantity" min="0" max="5" type="number" class="quantity" value="1" onclick="total(this.form);"/>
</td>
As you can see, I have explicitly defined the tabIndex and names.
Now for the JavaScript, I now use:
function total(frm)
{
var tot = 0;
var checkboxes = document.forms[frm.id].elements["checkbox"];
var quants = document.forms[frm.id].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
// if tabIndex correctly specified
if (checkboxes[i].tabIndex == quants[i].tabIndex)
// add to total
tot += Number(checkboxes[i].value) * Number(quants[i].value);
else
// notify of bug
alert('Bug in code: tabIndex of checkbox '+i+' is not the same as tabIndex quantity '+i);
}
}
document.getElementById("totalDiv").firstChild.data = "£" + tot;
}
By doing it this way you get the following advantages:
Your HTML code makes more sense (input elements are grouped per tabIndex)
Your code is checked for bugs
You are absolutely sure that you multiply the correct input elements
You can find this code in this jsFiddle.
Good luck! I hope this helps you out!
Update
To create a sort of checkout system, you could go over all the elements again and store them in a variable.
Then make sure that the form implements a function upon submit:
action="javascript:checkout()"
so in total:
<form action="javascript:checkout()" id="theForm">
Easiest way to create the message would be to use one variable like so:
function checkout()
{
var message = "";
var checkboxes = document.forms["theForm"].elements["checkbox"];
var quants = document.forms["theForm"].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
switch(checkboxes[i].tabIndex)
{
case 1: message += "iPhone"; break;
case 2: message += "Screen"; break;
case 3: message += "Laptop"; break;
case 4: message += "Coffee"; break;
default: message += "";
}
message += " Quantity: " + Number(quants[i].value) + " Price: £" + Number(checkboxes[i].value) * Number(quants[i].value) + "\n";
}
}
message += "\nTotal: " + document.getElementById("totalDiv").firstChild.data;
alert(message);
}
You can find a working implementation of this here.
Fancy solution
Or if you would like to make it a little bit more fancy, you could do the following:
Add the following HTML:
HTML
<br><br>
<div id="checkout">
<table id="myTable" border="1">
<tr>
<td>Product</td>
<td>Quantity</td>
<td>Price</td>
</tr>
</table>
</div>
Add the following JavaScript function:
JavaScript
function checkout()
{
document.getElementById("checkout").innerHTML = '<table id="myTable" border="1"><tr><td><b>Product</b></td><td><b>Quantity</b></td><td><b>Price</b></td></tr></table>';
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
var count = 0;
var max = 0;
var checkboxes = document.forms["theForm"].elements["checkbox"];
var quants = document.forms["theForm"].elements["quantity"];
for (var i = 0; i < checkboxes.length; i++)
{
if (checkboxes[i].checked)
{
switch(checkboxes[i].tabIndex)
{
case 1: message = "iPhone"; break;
case 2: message = "Screen"; break;
case 3: message = "Laptop"; break;
case 4: message = "Coffee"; break;
}
count += Number(quants[i].value);
max += 1;
// Create an empty <tr> element and add it to the table:
var row = table.insertRow(max);
// Insert new cells (<td> elements) at the 1st, 2nd and 3rd position
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
// Add some text to the new cells:
cell1.innerHTML = message;
cell2.innerHTML = Number(quants[i].value);
cell3.innerHTML = "£" + Number(checkboxes[i].value) * Number(quants[i].value);
}
}
// Calculate total
var row = table.insertRow(max+1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "<b>Total</b>";
cell2.innerHTML = count;
cell3.innerHTML = document.getElementById("totalDiv").firstChild.data;
}
The result looks like this:
You can find the corresponding jsFiddle HERE.
Hope that helps you out!