Creating a table using JavaScript - javascript

I am new to front-end web development and right now I am working on a test task to create a table using javascript.Here is my html file:
<title>Pixel Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="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="inputWeight" name="width" min="1" value="1">
<input type="submit" onclick="makeGrid()">
</form>
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
<script src="designs.js"></script> </body> </html>
And my javascript file:
function makeGrid() {
var rows=inputHeight; var cols=inputWeight; //Referencw for the body var body=document.getElementsbyTagName("body")[0];
//create a table element and a <tbody> element var table1=document.createElement("table"); var tableBody=document.createElement("tbody");
//creating cells for (var i=0;i<rows;i++){ //creating a table row var R=document.createElement("tr"); for(var j=0;j<cols;j++){ //create a table data element var C=document.createElement("td"); R.appendchild(C);
} //adding the row to the end of the table body
tableBody.appendChild(R); } //putting the <tbody> in the <table> table1.appendChild(tableBody); //appending <table> into <body> body.appendChild(table1);
}
I am supposed to get user input of rows and columns via submit button and generate a table according to that specification.So far my attmepts are unsuccessful,more precisely when I hit submit,nothing happens and the values revert back to "1".
I would really appreciate your guidance and feedback.

You don't need a <form>. There's nothing to submit to.
Use document.getElementById
You already have a <table id> in HTML. Reference it!
You don't need therefore a document.body reference.
To retrieve the integer use parseInt( number, radix ) since input value is a String
Clear your table from existing content before appending new stuff.
Use addEventListener(EventName, callback) instead of inline JavaScript (onclick)
Weight is not Width!
function makeGrid() {
var ELTable = document.getElementById("pixelCanvas"); // You already have it!
var ELInputHeight = document.getElementById("inputHeight");
var ELInputWidth = document.getElementById("inputWidth");
var rows = parseInt(ELInputHeight.value, 10);
var cols = parseInt(ELInputWidth.value, 10); // Weight? you mean Width!
ELTable.innerHTML = ""; // Empty table before inserting new stuff
var tbody = document.createElement("tbody");
for (var i = 0; i < rows; i++) { // N rows...
var R = document.createElement("tr"); // Make row.
for (var j = 0; j < cols; j++) { // N cells...
var C = document.createElement("td"); // Make cell.
R.appendChild(C); // Insert cell into row.
}
tbody.appendChild(R); // Insert row into tbody
}
ELTable.appendChild(tbody); // Insert tbody into table
}
document.getElementById("makeGrid").addEventListener("click", makeGrid);
td { padding:10px; background:#000; }
Height: <input type="number" id="inputHeight" min="1" value="1">
Width: <input type="number" id="inputWidth" min="1" value="1">
<button id="makeGrid">MAKE</button>
<br>
Color: <input type="color" id="colorPicker">
<table id="pixelCanvas"></table>

I create function for generate body of table, and listener for butto
function createTableBody(height, width) {
let tr = document.createElement('tr');
let td = document.createElement('td');
let docFr = new DocumentFragment();
for (let i = 0; i < width; i++) {
tr.append(td.cloneNode());
}
for (let i = 0; i < height; i++) {
docFr.append(tr.cloneNode(true));
}
return docFr;
}
let table = document.getElementById('pixelCanvas');
let createTableButton = document.getElementById('createTableButton');
let inputHeight = document.getElementById('inputHeight');
let inputWidth = document.getElementById('inputWeight');
createTableButton.addEventListener('click', () => {
let parentTable = table.parentNode;
let tableClone = table.cloneNode();
parentTable.replaceChild(tableClone, table);//clear old table
table = tableClone;
tableClone.append(createTableBody(inputHeight.value, inputWidth.value));
// if you need , you can add ajax request
console.log(table)
});
<title>Pixel Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="styles.css"> </head> <body>
<h1>Lab: Pixel Art Maker</h1>
<h2>Choose Grid Size</h2>
Grid Height:
<input type="number" id="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="1">
<input type="button" id="createTableButton">
<h2>Pick A Color</h2>
<input type="color" id="colorPicker">
<h2>Design Canvas</h2>
<table id="pixelCanvas"></table>
</body> </html>
If you need send data to server, you can use ajax, and i replace your submit to button, remove form.

Try this:
<form id="form-grid" method="post" onsubmit="makeGrid()">
<h2 id="grid-size">Choose Grid Size</h2>
<label for="inputHeight">Grid height:</label>
<input type="number" id="inputHeight" name="height" min="1" value="1" aria-describedby="grid-size" />
<label for="inputWeight">Grid width:</label>
<input type="number" id="inputWeight" name="width" min="1" value="1" aria-describedby="grid-size" />
<h2>Pick a color</h2>
<label for="colorPicker">Color:</label>
<input type="color" id="colorPicker" name="color" />
<input type="submit" value="Make Grid" />
</form>
<div id="pixelCanvas"></div>
Do note the addition of explicit label's here. These are important for accessibility!
I've added a submit handler to the form, and removed it from the button. I find it's a bit cleaner, but your approach would ultimately work too.
Then in your designs.js file, you might have:
function makeGrid(event) {
event.preventDefault(); // prevents the form from submitting
var form = document.querySelector('#form-grid');
var rows = form.querySelector('#inputHeight').value;
var cols = form.querySelector('#inputWeight').value;
var wrapper = document.querySelector('#pixelCanvas');
var table = document.createElement('table');
for (var r = 0; r < rows; r++) {
var tr = table.insertRow();
for (var c = 0; c < cols; c++) {
var td = tr.insertCell();
}
}
wrapper.appendChild(table);
}
A few reminders:
Use label to associate a form field with it's visible label. This is necessary for assistive technology such as screen readers.
Consider a fieldset to group all of the options, increasing its accessibility.
Good luck!

As #Katamari said, it looks like you're not properly accessing the elements and getting their values.
To access an element, you can use document.querySelector and pass in a CSS selector.
var rowInput = document.querySelector("#inputHeight");
var colInput = document.querySelector("#inputWidth");
Since you have assigned IDs, you could use document.getElementById
var rowInput = document.getElementById("inputHeight");
var colInput = document.getElementById("inputWidth");
Either way, you'll get an element or null if the element can't be found. Once you have the element, just get the value property to get the user results.
var rows = rowInput.value;
var cols = colInput.value;
If you want to avoid error that could be caused by not finding the element, you can check for the element before referencing the value.
var rows = 1;
var cols = 1;
if (rowInput) {
rows = rowInput.value;
}
if (colInput) {
cols = colInput.value;
}
This can be converted into a single line using a tenary operator
var rows = rowInput
? rowInput.value
: 1;
var cols = colInput
? colInput.value
: 1;

Related

Udacity pixel art lab

So I am trying to solve a lab that requires to build a color picker and a grid. By clicking on a particular cell, it gets colored with the color you picked. I passed 4/5 tests, the test that fails gives me: App functionality Picking a new color and clicking a cell displays the new color.
Even though when I test it, it works, I can change the color of cells.
javaScript Code:
// Select color input
var color;
function selectColor()
{
color = document.getElementById("colorPicker").value;
}
// Select size input
var height;
var width;
// When size is submitted by the user, call makeGrid()
var s = document.getElementById("sizePicker");
s.addEventListener('submit',function makeGrid(e)
{
e.preventDefault();
var height = parseInt(document.getElementById("inputHeight").value);
var width = parseInt(document.getElementById("inputWidth").value);
var t = document.getElementById("pixelCanvas");
while(t.firstChild)
{
t.removeChild(t.firstChild);
}
for(var i = 0;i < height; i++)
{
var r = document.createElement("tr");
t.appendChild(r);
for(var j = 0; j < width; j++)
{
var c = document.createElement("td");
r.appendChild(c);
}
}
var pixel = document.querySelectorAll("td");
pixel.forEach(myfunction);
function myfunction(item,index)
{
selectColor();
item.addEventListener('click', function(evt){
evt.preventDefault();
item.style.backgroundColor = color;})
}
})
Html code:
<!DOCTYPE html>
<html>
<head>
<title>Pixel Art Maker!</title>
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Monoton">
<link rel="stylesheet" href="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" oninput="selectColor()">
<h2>Design Canvas</h2>
<table id="pixelCanvas" border = 1>
</table>
<script src="designs.js"></script>
</body>
</html>
codepen:
https://codepen.io/AMMAROVA/pen/QWQPLVJ
This is my first question on this website so excuse me if it wasn't clear enough.

How do I make a dynamic drop down menu using JavaScript

I have it so you type in on a form a maximum number then it creates a table after clicking a button.
I want it so after you click the button to add the row it writes a drop down menu in the table that goes from 0 to the number you put in the form
This is my HTML code:
<html>
<head>
<title>Form Generator</title>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<script language="JavaScript" src="../js/exercise2.js" type="text/javascript">
</script>
</head>
<body>
<p>
<button class="button" data-modal="M2KM">Form Generator</button>
</p>
<div id="M2KM" class="modal">
<div class="modal-content">
<div class="form">
<a class="close">×</a>
<form action="">
<textarea rows="1" name="Section" id="Section" cols="10">Section</textarea>
<textarea rows="1" name="Max" id="Max" cols="10">Max</textarea>
<textarea rows="1" name="Comment" id="Comment" cols="10">Comment</textarea>
<textarea rows="1" name="Mark" id="Mark" cols="10">Mark</textarea>
<input type="button" value="Add Row" name="Add Row" onclick="conversionTable('table')" />
<input type="reset" value="Clear" name="Clear">
</form>
<div id="conversion">
<table id="table">
<thead>
<tr>
<th>Section</th>
<th>Max</th>
<th>Comment</th>
<th>Mark</th>
</tr>
</thead>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
This is my JavaScript Code:
function conversionTable(tagId, from, to)
{
var section = document.getElementById("Section").value;
var max = document.getElementById("Max").value;
var comment = document.getElementById("Comment").value;
var mark = document.getElementById("Mark").value;
from = 0;
to = 1;
var total = 0;
var arr = [];
var conv = document.getElementById(tagId) ;
var pre = document.createElement("pre");
conv.appendChild(pre);
var body= conv.appendChild(document.createElement("tbody"));
for (var i=from; i<to; i++)
{ row = body.appendChild(document.createElement("tr"));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(section));
data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(max));
var data=row.appendChild(document.createElement("td"));
data.appendChild(document.createTextNode(comment));
data=row.appendChild(document.createElement("select"));
data.setAttribute("id", "mySelect");
row.appendChild(data);
var z = document.createElement("option");
z.setAttribute("value", "volvocar");
var t = document.createTextNode("1");
z.appendChild(t);
document.getElementById("mySelect").appendChild(z);
total = total + mark;
var obj = {section: section, max: max, comment: comment, mark: mark};
arr.push(obj);
}
}
This is a screenshot showing test data:
Here's a simplified example that adds a select element with a number of options equal to the number entered by the user.
See comments in the code for an explanation of how it works.
// Identifies existing HTML elements
const maxInput = document.getElementById("max");
const button = document.getElementById("button");
const table = document.getElementById("table");
// Calls `addDropdown` when `button` is clicked
button.addEventListener("click", addDropdown);
// Defines the event listener
function addDropdown(event) { //(`event` object is available if we want it)
// Gets value from input
let max = parseInt(maxInput.value);
// Exits function early if maxInput doesn't have a number
if(!max){ return; }
// Defines the new elements
const row = document.createElement("tr");
const cell = document.createElement("td");
const dropdown = document.createElement("select");
// Enumerates options and adds them to the select element
let optNumber = -1;
while(++optNumber <= max){
let optionElement = document.createElement("option");
optionElement.value = "opt" + optNumber;
optionElement.innerHTML = "Option " + optNumber;
dropdown.appendChild(optionElement);
}
// Adds the elements to the page
cell.appendChild(dropdown);
row.appendChild(cell);
table.appendChild(row);
}
<label>
<span>Enter maximum value for dropdown:</span>
<input id="max" value="5" />
</label>
<br />
<button id="button">Add Dropdown in New Row</button>
<div id="container">
<table id="table"></table>
</div>

Dynamic tables printing wrong row and columns in html and jquery

I'm trying to dynamically generate a table on my website but it's giving me the wrong rows(width) and column(height)
For an input of row=1 and column=4 it generates a tables of 2 rows with 1 row of 5 columns and the other with 4 columns
$("#sizePicker").submit(function(event) {
var height = event.currentTarget[0].value,
width = event.currentTarget[1].value;
console.log(height + "width" + width);
for (var i = 0; i < height; i++) {
console.log(i);
$('#pixelCanvas').append("<tr>");
for (j = 0; j < width; j++) {
console.log(j);
$('tr').append("<td></td>");
}
$('#pixelCanvas').append("</tr>");
}
event.preventDefault();
});
<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="inputHeight" name="height" min="1" value="1"> Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="1">
<input id="click" type="submit">
</form>
<table id="pixelCanvas">
</table>
It is happening because you append td to every tr that is in table.
This is wrong
Here is an working example
$("#sizePicker").submit(function(event) {
var table = $('#pixelCanvas'),
height = event.currentTarget[0].value,
width = event.currentTarget[1].value;
console.log("height: " + height + ", width: " + width);
table.html("");
for (var i = 0; i < height; i++) {
table.append("<tr class='row" + i +"'></tr>");
for (j = 0; j < width; j++) {
$("tr.row" + i).append("<td>" + i + j + "</td>");
}
}
event.preventDefault();
});
<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="inputHeight" name="height" min="1" value="4"> Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="5">
<input id="click" type="submit">
</form>
<table id="pixelCanvas">
</table>
According to your logic td goes on appending inside every tr as loop goes. So you need to append td to this tr not on all tr inside table. Here is an working example.
$(function() {
$("#click").on('click', function(event) {
var height = $('#inputHeight').val();
var width = $('#inputWeight').val();
var html = '';
for (var i=0;i<height;i++)
{
html +='<tr>';
for (j=0;j<width;j++)
{
html+= "<td>"+i + '' + j+"</td>";
}
html += ("</tr>");
}
$('#pixelCanvas').html(html);
});
});
<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="inputHeight" name="height" min="1" value="1">
Grid Width:
<input type="number" id="inputWeight" name="width" min="1" value="1">
<input id="click" type="button" value="submit">
</form>
<table id="pixelCanvas">
</table>
The issue is because you append a new td to every tr that exists in the table, even those created in previous iterations.
You can fix this, and improve the logic, by creating arrays containing the td and tr elements based on the extents specified in the input values. Something like this:
$("#sizePicker").submit(function(e) {
e.preventDefault();
var height = parseInt($('#inputHeight').val(), 10);
var width = parseInt($('#inputWeight').val(), 10);
var columns = new Array(width).fill('<td></td>').join('');
var rows = new Array(height).fill(`<tr>${columns}</tr>`);
$('#pixelCanvas').html(rows.join(''));
});
table {
margin: 10px;
}
table td {
padding: 5px 20px;
border: 1px solid #CCC;
}
<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="inputHeight" name="height" min="1" value="5"><br />
Grid Width: <input type="number" id="inputWeight" name="width" min="1" value="5"><br />
<input id="click" type="submit">
</form>
<table id="pixelCanvas"></table>
I found the error in your script, this is how the submit function should look like:
$("#sizePicker").submit(function(event) {
height = parseInt(event.currentTarget[0].value),
width = parseInt(event.currentTarget[1].value);
console.log(height + "width" + width);
for (var i = 0; i < height; i++)
{
if(height>0)
{
let tr = $('<tr></tr>');
for (j = 0; j < width; j++)
{
tr.append("<td></td>");
}
$('#pixelCanvas').append(tr);
}
}
event.preventDefault();
});

To use the data from input tag in html in javascript

I want to use the data from input tags in html. The html code is shown below.
<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">
The data values from input tags should be used in javascript code shown below:
function makeGrid() {
for(let td_row=0; td_row < 6; td_row++){
$(<tr></tr>).appendTo(<table id="pixel_canvas"></table>);
for(let td_cell =0; td_cell < 6; td_cell++){
$(<td></td>).appendTo(<tr></tr>);
}
}
Can somebody please help me in this?
Try this solution. Get the values from the inputs and set them as the range for the conditions in the loops. Then add your create tr in the first loop, in the second one append td to it. After all append the tr with tds to the table.
const table = $('#pixel_canvas');
const inputHeight = $('#input_height');
const inputWidth = $('#input_width');
function makeGrid() {
const height = parseInt(inputHeight.val());
const width = parseInt(inputWidth.val());
for(let row = 0; row < height; row++) {
const tr = $('<tr></tr>');
for(let cell = 0; cell < width; cell++) {
tr.append(`<td>${row}${cell}</td>`);
}
table.append(tr);
}
}
$('#submitBtn').on('click', makeGrid);
<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">
<button id="submitBtn" type="button">Generate</button>
<table id="pixel_canvas">
</table>
You need to use strings, when creating HTML element (e.g. $('')) instead of raw markup. I updated the function from the question, so that it creates a table and returns it. You only need to insert it wherever you need.
function makeGrid() {
var rowsCount = ParseInt($('#input_height').val()) || 0;
var columnsCount = ParseInt($('#input_width).val()) || 0;
var table = $('<table id="pixel_canvas"></table>');
for(let td_row = 0; td_row < rowsCount; td_row++){
var tr = $('<tr></tr>').appendTo(table);
for(let td_cell = 0; td_cell < columnsCount; td_cell++){
$('<td></td>').appendTo(tr);
}
}
return table;
}

Convert Miles to Kilometers in a range given by the user and display them in a list

I am required to write the code using three files, Javascript, HTML, and CSS. I am not sure what is the problem in my code, please help me find the error. The user is to write the range in two textareas and when a button is clicked convert all values starting from the first given number up to the second given number. This is what I have written so far:
HTML code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<title>Celsius to Fahrenheit Converter</title>
<script language="JavaScript" src="../js/c2f.js" type="text/javascript">
</script>
</head>
<body>
<h2>Miles to Kilometers Converter</h2>
<form action="">
<p>
<textarea rows="1" name="Input1" id="Input1" cols="10"></textarea>
<textarea rows="1" name="Input2" id="Input2" cols="10"></textarea>
<input type="button" value="Convert" name="B3" onclick="conversionTable()">
<input type="reset" value="Clear" name="B2">
</p>
</form>
<div id="conversion">
</div>
</body>
</html>
JavaScript code:
function conversionTable(tagId, from, to)
{
var first = document.getElementById("Input1");
var second = document.getElementById("Input2");
from =first;
to = second;
var conv = document.getElementById(tagId);
var tab = document.createElement("table");
var bod = document.createElement("tbody");
var thed = document.createElement("thead");
tab.appendChild(thed);
tab.appendChild(bod);
var tr = document.createElement("tr");
thed.appendChild(tr);
var th = document.createElement("th");
tr.appendChild(th);
th.appendChild(document.createTextNode("Miles"));
th = document.createElement("th");
tr.appendChild(th);
th.appendChild(document.createTextNode("Kilometers"));
conv.appendChild(tab);
for(var i=from; i<=to; i++){
tr = document.createElement("tr");
if (i%2==0)
tr.setAttribute("class", "even");
else
tr.setAttribute("class", "odd");
bod.appendChild(tr);
td = document.createElement("td");
tr.appendChild(td);
td.appendChild(document.createTextNode(i));
td = document.createElement("td");
tr.appendChild(td);
td.appendChild(document.createTextNode(c2f(i)));
}
function c2f(c) {return Math.round((c * 1.6093)*10)/10}
}
CSS code:
h2{text-align:center; color:blue; background: #EFEFEF}
body{margin: 4em; width: 400px}
table{margin: 2em; padding: 1em;}
th{background: #EFEFFF}
tr.even {background: #B8B8B8}
tr.odd {background: #E0FFFF}
So again, I am trying to pass the two variables (first and second) into my conversionTable() function.
DEMO HERE
Changes to your html:
<input type="button" value="Convert" name="B3" onclick="conversionTable('conversion')" />
Changes to your js:
from = parseInt(first.value);
to = parseInt(second.value);
and thats it. It should work to what you're looking for.
An exmaple of using plain javascript to build the conversion table:
<form action="">
<p>
<textarea rows="1" name="Input1" cols="10"></textarea>
<textarea rows="1" name="Input2" cols="10"></textarea>
<input type="button" value="Convert" name="B3" onclick="buildConversionTable(this);">
<input type="reset" value="Clear" name="B2">
</p>
</form>
<div id="conversion"></div>
<script>
// Convert miles to kilometres, round to 2 places
function m2k(c) {
return (c * 1.6093).toFixed(2); // returns a string
}
// Return a new element with provided tag name and properties
function newElement(tagName,props) {
var el = document.createElement(tagName);
if (props) {
for (var prop in props) {
if (props.hasOwnProperty(prop)) {
el[prop] = props[prop];
}
}
}
return el;
}
// Return a new text node with text as content
function newText(text) {
return document.createTextNode(text);
}
// Create the conversion table
function buildConversionTable(button) {
var form = button.form;
var from = form.Input1.value;
var to = form.Input2.value;
// Use a temporary element to build the tabel from HTML
var d = document.createElement('div');
d.innerHTML = '<table><thead><tr><th>Miles<th>Kilometres</thead></table>';
var table = d.getElementsByTagName('table')[0];
// Tables always have at least one tbody, no need for tags in the HTML
var tbody = table.tBodies[0]
// Use the convenience of appendChild returning the appended element
for (var i=from, row, cell; i<=to; i++) {
row = tbody.appendChild(newElement('tr',{className: i%2? 'odd':'even'}));
cell = row.appendChild(newElement('td'));
cell.appendChild(newText(i));
cell = row.appendChild(newElement('td'));
cell.appendChild(newText(m2k(i)));
}
// Add the table to the document
document.getElementById('conversion').appendChild(table);
}
</script>
Oh, forgot about the DOM table methods. The for loop adding the rows can be:
for (var i=from, row, cell; i<=to; i++) {
row = tbody.insertRow(-1);
row.insertCell(-1);
row.insertCell(-1);
row.className = i%2? 'odd':'even';
row.cells[0].innerHTML = i;
row.cells[1].innerHTML = m2k(i);
}
I would recommend using jQuery to solve this problem. To include jquery in your project change your html to this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="../css/converter.css"/>
<title>Celsius to Fahrenheit Converter</title>
<script language="JavaScript" src="../js/c2f.js" type="text/javascript">
</script>
<!-- Here is your jquery code includer -->
<script src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
</head>
<body>
<h2>Miles to Kilometers Converter</h2>
<form action="">
<p>
<textarea rows="1" name="Input1" id="Input1" cols="10"></textarea>
<textarea rows="1" name="Input2" id="Input2" cols="10"></textarea>
<input type="button" value="Convert" id="convert" name="B3" />
<input type="reset" value="Clear" name="B2" />
</p>
</form>
<div id="conversion"></div>
</body>
</html>
Using jQuery you can add the click handler to the convert button and in there calculate the from and to and call the conversionTable function. I have revised the conversionTable function to do what you want in much less code using jQuery.
$("#convert").click(function () {
var from = parseInt($("#Input1").val());
var to = parseInt($("#Input2").val());
conversionTable($("#conversion"), from, to);
});
function conversionTable(tag, from, to) {
//Generate the table with the thead of miles and kilometers
var table = $("<table><thead>" +
"<tr><th>Miles</th><th>Kilometers</th></tr>" +
"</thead><tbody></tbody></table>");
//set the tags innerHtml to the table
tag.html(table);
for (var i = from; i <= to; i++) {
var miles = i;
var kilometers = c2f(i);
//Create a tr with the found miles and kilometers
var tr = $("<tr><td>" + miles + "</td><td>" + kilometers + "</td></tr>");
//Add the tr to the tables tbody
table.find("tbody").append(tr);
}
//Find all of the even and odd tr's and give them the appropriate class
table.find("tr:even").addClass("even");
table.find("tr:odd").addClass("odd");
function c2f(c) {
return Math.round((c * 1.6093) * 10) / 10;
}
}
Your css would stay the same as previously posted. You can find a working jsFiddle at http://jsfiddle.net/FsV3j/.

Categories

Resources