How to pass values from javascript to html? - javascript

I am trying to generate multiplication tables in JavaScript and pass the values to the rows of a table in html. I want an output like the image shown. Can anyone help me with this. I'm new to Javascript and am trying to figure out some of the basics. Thanks.
<html>
<head>
<title>Multiplication Table Generator</title>
<script language="javascript" type="text/javascript">
function generateTable()
{
var myVar = prompt("A number?", "");
var myVar = multTables.number.value;
var myString = "";
for (i=1; i<=myVar; i++) {
myString += i+ " x " +myVar+ " = " +(i*myVar)+ "\n";
}
}
</script>
</head>
<body>
<h1>Times Tables</h1>
<form name="multTables">
Enter a number<input type=text name="number">
<input type=button name="button1" value="Show Table" onclick="generateTable()">
<table border=1>
<tr><th>times tables</th></tr>
<tr><td>
<!-- 1X7, 2X7...etc-->
</td>
<td>
<!-- 7, 14, 21...etc-->
</td>
</tr>
</table>
</form>
</body>
</html>

I don't understand why you are using html form and js prompt at the same time.
Ok, you can use this :
<html>
<head>
<title>Multiplication Table Generator</title>
<script language="javascript" type="text/javascript">
function generateTable()
{
//var myVar = prompt("A number?", "");
var myVar = document.forms.multTables.x.value;
var myString = "<tr><th>"+ myVar + " times tables</th></tr>";
for (i=1; i<=myVar; i++)
{
myString += "<tr><td>";
myString += i+ " x " +myVar+ " = " +(i*myVar)+ "\n";
myString += "</td></tr>";
}
document.getElementById('t').innerHTML = myString;
return false;
}
</script>
</head>
<body>
<h1>Times Tables</h1>
<form name="multTables">
Enter a number<input type="text" name="number" id="x">
<input type="button" name="button1" value="Show Table" onclick="generateTable()">
<table border="1" id="t">
</table>
</form>
</body>
</html>

Okay so I set up a small example here that should give you a nice example of how to do this:
http://jsfiddle.net/MHfyE/
HTML:
<div id="content">
</div>
<button id="button">Do It!</button>
Javascript:
var buttonElt = document.getElementById("button");
buttonElt.onclick = function() {
var elt = document.createElement("div");
for (var i = 0; i < 10; i++) {
var childElt = document.createElement("p");
childElt.innerHTML = i;
elt.appendChild(childElt);
}
var parentElt = document.getElementById("content");
parentElt.appendChild(elt);
}
I feel like this is enough to get you started.

First, you're overwriting myVar right after asking it in the prompt, doesn't make much sense.
var myVar = prompt("Give me my var!");
console.log(myVar);
Then you'll somehow have to generate the HTML, you can do it by using jQuery and appending elements or vanilla JS or just generating the raw HTML string. Or using something like AngularJS's ng-repeat.
Here's a really simple example:
var table = document.createElement("table");
for (var i = 0; i < 10; i += 1) {
var tableRow = document.createElement("tr");
for (var j = 0; j < 10; j += 1) {
var tableCell = document.createElement("td");
tableCell.innerHTML = i * j;
tableRow.appendChild(tableCell);
}
table.appendChild(tableRow);
}
Fiddle:
http://jsfiddle.net/jbNbs/1/

Here is a simple example ....
This way, the table is NOT generated by the JavaScript.
JavaScript fills the cell data.
Enter a number in the box, hit enter
If the entry is not a number, it will reject it (won't do anything)
The JavaScript
function generateTable(n) {
n = parseInt(n); // convert to integer
if (!n) { return; } // end execution if not found
// get all the tr in the table
var tr = document.querySelectorAll('#timesTable tr');
tr[0].children[0].textContent = n + ' Times Table';
for (var i = 1; i <= 9; i++) {
tr[i].children[0].textContent = i + ' x ' + n + ' =';
tr[i].children[1].textContent = i * n;
}
}
The HTML
Enter a number: <input type="text" id="box" onchange="generateTable(this.value);">
<br /><br />
<h1>Times Tables</h1>
<table id="timesTable" border="1">
<tr><th colspan="2">Times Table</th></tr>
<tr><td style="width: 100px;"> </td><td style="width: 50px;"> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
<tr><td> </td><td> </td></tr>
</table>
Good luck
:)

Related

How to fix undefined array

I am fairly new to javascript so any assistance is appreciated. I am trying to collect 2 related inputs from a user and display the array object as a table. When the inputs are submitted however, the array is displaying as undefined. I am not sure where I am going wrong. Any suggestions?
I have tried different methods of collecting the inputs off the form but none seem to work.
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Example:</title>
<script type="text/javascript">
var flights = [];
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
function render() {
document.getElementById("mydiv").innerHTML = "";
thelisthtml = "";
for(i = 0; i< flights.length; i++)
thelisthtml += "<div class='card' id="+ i +"><div class='card-body'>";
thelisthtml += "Flight " + (i+1) + " : " + flights[i] + " " + "<button type='submit' onclick = 'clearToDo(this)' id="+ i +">Remove From List</button>";
document.getElementById("mydiv").innerHTML = thelisthtml;
}
function calculateStatus(){
var totalMiles = Number(document.getElementById("totalMiles").value);
if (miles < 9999){
tr = document.getElementById("table").rows[1];
tr.style.backgroundColor = "yellow";
}
if (miles >= 10000 && miles <= 24999){
tr = document.getElementById("table").rows[2];
tr.style.backgroundColor = "yellow";
}
if (miles >= 25000){
tr = document.getElementById("table").rows[3];
tr.style.backgroundColor = "yellow";
}
}
function refreshPage() {
window.location.reload();
}
</script>
</head>
<body>
<br>
<table id="table" border ="1">
<tr>
<th>Medallion Status</th>
<th>Level</th>
</tr>
<tr>
<td>Bronze</td>
<td> < 10000 miles</td>
</tr>
<tr>
<td>Silver</td>
<td> < 25000 miles</td>
</tr>
<tr>
<td>Gold</td>
<td> > 25000</td>
</tr>
</table>
<h1><strong>Traveler Information </strong></h1><br> <br>
Flight Number: <input type="text" id="number" name="number" value="" />
<br> <br>
Miles Flown: <input type="text" id="miles" name="miles" value=""/> <br>
<br>
<input type="submit" value="Add Flight" id="go" onclick="add(this)"/>
<p>----------------------------</p>
<table>
<thead>
<tr>
<th>Flight</th>
<th>Miles</th>
</tr>
<thead>
<tbody>
<tr class="col-md-6" id="mydiv"></tr>
</tbody>
</table>
<input type="reset" id="reset" name="Reset" value="Reset"
onclick="refreshPage()" /> <br> <br> <br>
<br> <br>
</body>
</html>
the expected result is the array will display in a table as the user enters information. the actual result is the array is undefined.
There are several issues but the answer to your question about how to fix the flights array containing undefined is to change
function add(ele) {
flights.push(number, miles);
render();
document.getElementById("number").value = "";
document.getElementById("miles").value = "";
}
to
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push(numberElem.value, milesElem.value);
render();
numberElem.value = "";
milesElem.value = "";
}
In your original add function you are pushing number and miles onto the flights array but number and miles are undefined variables so you are pushing undefined and undefined onto the flights array.
To also fix the other issues I'd suggest replacing your add and render functions with the follow
function add() {
const numberElem = document.getElementById("number");
const milesElem = document.getElementById("miles");
flights.push({
number: numberElem.value,
miles: milesElem.value});
render();
numberElem.value = "";
milesElem.value = "";
}
function render() {
const tbody = document.querySelector('#outputTable tbody');
tbody.innerHTML = flights.map((flight, i) => {
return ''
+ '<tr>'
+ '<td>'
+ flight.number
+ '</td>'
+ '<td>'
+ flight.miles
+ '</td>'
+ '<td>'
+ `<button type='button' onclick="clearToDo(${i})">`
+ 'Remove From List'
+ '</button>'
+ '</td>'
+ '</tr>';
}).join('');
}
and changing your second <table> to <table id="outputTable">.

Javascript writing into Table not working

I just decided to code a little html file which should create a multiplication table with integers from "start" to "end". Start and End are set before in a HTMl Form...
I can give 2 numbers as input and the tr and td elements are create but accessing them by ClassName and filling them with innerHTML does somehow not work.
Here is the Code:
<html>
<head>
<title>Das groࠥ 1x1</title>
<meta charset="utf-8">
</head>
<script type="text/javascript">
function malnehmen(Wert1, Wert2) {
Ausgabe = Wert1 * Wert2;
return Ausgabe;
}
function tabelle() {
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(i = start; i < end+1; i++) {
Reihe = document.createElement("tr");
att = document.createAttribute("class");
att.value = i + "a";
Reihe.setAttributeNode(att);
document.getElementById("Darein").appendChild(Reihe);
for(ii = start; ii < end+1; ii++) {
Feld = document.createElement("td");
att2 = document.createAttribute("class");
att2.value = malnehmen(i, ii);
Feld.setAttributeNode(att2);
Reihe.appendChild(Feld);
}
}
}
function ausfuellen() {
tabelle();
var start = document.forms["printer"].anfang.value;
var end = document.forms["printer"].ende.value;
for(a = start; a < end+1; a++) {
alert("Hier denn?");
document.getElementsByClassName(a + "a").innerHTML = a.toString();
for(aa = start; aa < end+1; aa++) {
multi = malnehmen(a, aa);
alert("Angekommen");
document.getElementsByClassName(multi).innerHTML = multi.toString();
}
}
}
</script>
<body>
<FORM name="printer">
<TABLE>
<tr>
<td>Beginnt bei:</td>
<td>
<input type="number" name="anfang" size="3">
</td>
</tr>
<tr>
<td>Endet bei:</td>
<td>
<input type="number" name="ende" size="3">
</td>
</tr>
<tr>
<td>
<input type="button" name="wassolldas" value="Erstellen" onclick="javascript: tabelle();">
</td>
</tr>
</TABLE>
</FORM>
<br>
<TABLE id="Darein" border="1">
</TABLE>
</body>
Does anybody know what I did wrong?
I built in 2 alerts just to see if the javascript part reaches the for loop but there is no pop up in browser.

How to get the value of html <input type=“hidden” id="hide"> in PHP?

This is for generating the table.
function makeTable()
{
var row_num = 20;
var cell_num = 4;
var tab = document.createElement('table');
tab.setAttribute('id','newtable');
var tbo = document.createElement('tbody');
tbo.setAttribute('id','tabody');
var cont;
for(var c = 0 ; c < row_num ; c++)
{
var row = document.createElement('tr');
for(var k = 0 ; k < cell_num ; k++)
{
var cell = document.createElement('td');
if (k > 0)
{
cont = document.createElement("input");
cont.setAttribute('type','text');
}
else
{
cont = document.createTextNode("0" + (c+1));
}
cell.appendChild(cont);
row.appendChild(cell);
}
tbo.appendChild(row);
}
tab.appendChild(tbo);
document.body.appendChild(tab);
tab.setAttribute("align", "top-left");
}
This function is used to show the data in alert box but I want to retrieve document.getElementById('hide').value............
function GetCellValues()
{
var rows = document.getElementsByTagName('tr');
var str = '';
for (var c = 1 ; c < rows.length ; c++)
{
str += '\n';
var row = rows[c];
var inputs = row.getElementsByTagName('input');
for (var k = 0 ; k < inputs.length ; k++)
{
str += inputs[k].value + ', ';
}
}
document.getElementById('hide').value = str;
I want to retrieve only this hidden control (i.e-"hide") in php.
alert(document.getElementById('hide').value);
}
window.onload = function()
{
makeTable();
};
</script>
</head>
<body>
<h1><u>PROJECT</u> :</h1>
<input type="button" value="Alert" onclick = "GetCellValues()">
I want to retrieve this id in php
<input type="hidden" id="hide" /> <br />
<div id="mytable">
<table id = "project" border = "1" width ="60%" class = "newtable" cellpadding="10" cellspacing="0">
<tr>
<th align="center" width ="200px">Sl.No.</th>
<th align="center" width ="200px">Project Name</th>
<th align="center" width ="200px">ChangeDate</th>
<th align="center" width ="200px">Changed By</th>
</tr>
</table>
</div>
</body>
Note: I want to retrieve the hidden control through id in php ##
I want the total php code to retrieve this hidden control data(i.e-input type="hidden" id="hide") because I'm a beginner
You have to add a name to your input so for example:
<input type="hidden" id="hide" name="foo" />
To retrieve the value in php after POST form submission you can do this:
<?php $var1 = $_POST["foo"]; ?>
Can you please replace this line
<input type="hidden" id="hide" />
to
<input type="hidden" id="hide" name="hide" />
and use $_POST["hide"] in you php script.
Input field must have some name to access it
<input type="hidden" id="hide" name="hide" />
do normal fetch
$name = $_POST['hide'];
add name property to input type and value you want to get into you php
<input type="hidden" id="hide" name="flag" value="1" />
and to retrieve the value in php after POST form
$var1 = $_POST["flag"];

Populate Drop Down List Box with values from array

I have a requirement to populate a drop down list box in my form with human races. I believe I've done it correctly but I get an error that says Error: Unable to get property 'appendChild' of undefined or null reference
What am I doing wrong?
HTML:
<!DOCTYPE html />
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="TheCSS.css" />
<style type="text/css">
.style1 {
height: 26px;
}
</style>
</head>
<body>
<script type="text/javascript" src="C:\Users\Marc\Desktop\JavaScript Projects\TheJavaScript.js"></script>
<center>
<table class="style1">
<tr>
<td colspan="4">
<center>
<h1><b>New Hire Form</b></h1>
</center>
</td>
</tr>
<tr>
<td id="subHeader" colspan="4"></td>
</tr>
<tr>
<td class="style3">First Name</td>
<td class="style2">
<input type="text" id="FirstName" onchange="return LastName_onchange()" />
</td>
<td class="style4">Last Name</td>
<td>
<input id="LastName" type="text" onchange="return FirstName_onchange()" />
</td>
</tr>
<tr>
<td class="style1">Sex</td>
<td class="style1">Male
<input id="Radio1" checked="true" name="R1" type="radio" value="M" /> Female
<input id="Radio1" checked="true" name="R1" type="radio" value="F" />
</td>
<td class="style1">Race</td>
<td class="style1">
<select id="RaceDropDown" name="D1"></select>
</td>
</tr>
<tr>
<td class="style3"> </td>
<td class="style2"> </td>
<td class="style4">
<input type="button" id="myButt" value="Submit Entry" onclick="return myButt_onclick()" />
</td>
<td> </td>
</tr>
</table>
</center>
</body>
</html>
JavaScript:
var select = document.getElementById('RaceDropDown');
var options = ["Asian", "Black"];
var i;
for (i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
function LastName_onchange() {
var LastName = document.getElementById('LastName').value;
var FirstName = document.getElementById('FirstName').value;
document.getElementById('subHeader').textContent = FirstName + " " + LastName + " " + new Date();
}
function FirstName_onchange() {
var LastName = document.getElementById('LastName').value;
var FirstName = document.getElementById('FirstName').value;
document.getElementById('subHeader').textContent = FirstName + " " + LastName + " " + new Date();
}
CSS:
#subHeader
{
text-align: right;
}
Change this:
for (i = 0; i <= options.length; i++)
to
for (i = 0; i < options.length; i++)
Just need to do < . not <=
As mentioned in my comments, the script should be called after the element is created. If not, the script would throw an error because it will not find the select element to add options.
Please create a function for populating the drop-down and call it onload like the below:
function popDropDown() {
var select = document.getElementById('RaceDropDown');
var options = ["Asian", "Black", "White"];
var i;
for (i = 0; i < options.length; i++) {
var opt = options[i];
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
}
}
window.onload = popDropDown;
As an aside, in the for loop i < options.length is enough instead of i <= options.length.

submit two form contents onto one action page

i have two Forms to be submitted to a single destination page.
<form name= "form1" id="form1" action="final.php">
<input type="box1" name="box1" value="" >
</form>
<form name ="form2" id="form2" action="final.php">
<table>
<input type ="text" id="txt_1" name ="txt_1" value="">
...
</table>
</form>
<input type= "button" name="mybutton" id="mybutton" onclick="somefunction();">
here ,
form1 has some satic contents
and
form2 has a table which is dynamically generated by js...
problem is ...i want to submitted values from both the forms to same page final.php ...how cud i do it .....pls avoid jquery/ajax...
simple javascript welcomed ...
thanks in advance !
this is the js for generating dynamic table in form2
<script type="text/javascript">
function viewsource() {
alert(document.body.innerHTML);
}
</script>
<script type="text/javascript">
function addRowToTable()
{
var tbl = document.getElementById('tblSample');
var frm=document.form2;
if (!frm.ary) frm.ary=[frm.t1_1,frm.t1_2,frm.t1_3];
var lastRow = tbl.rows.length;
// if there's no header row in the table, then iteration = lastRow + 1
var iteration = lastRow;
var row = tbl.insertRow(lastRow);
// numberd row
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
// Item row
var cellRight1 = row.insertCell(1);
var el1 = document.createElement('input');
frm.ary.push(el1);
el1.type = 'text';
el1.value = '';
el1.name = 't' + iteration + '_1';
el1.id = 't' + iteration + '_1';
el1.size = 13;
el1.onkeyup=Calc;
el1.onblur=Calc;
cellRight1.appendChild(el1);
// Price row
var cellRight2 = row.insertCell(2);
var el2 = document.createElement('input');
frm.ary.push(el2);
el2.type = 'text';
el2.value = '';
el2.name = 't' + iteration + '_2';
el2.id = 't' + iteration + '_2';
el2.size = 10;
el2.onkeyup=Calc;
el2.onblur=Calc;
cellRight2.appendChild(el2);
// Price row
var cellRight3 = row.insertCell(3);
var el3 = document.createElement('input');
frm.ary.push(el3);
el3.type = 'text';
el3.value = '0';
el3.name = 't' + iteration + '_3';
el3.id = 't' + iteration + '_3';
el3.size = 10;
cellRight3.appendChild(el3);
}
function removeRowFromTable()
{
var tbl = document.getElementById('tblSample');
var lastRow = tbl.rows.length;
if (lastRow > 3) tbl.deleteRow(lastRow - 1);
}
function formReset()
{
document.getElementById("form2").reset();
}
</script>
<script type="text/javascript">
function Calc(){
var frm=document.form2;
if (!frm.ary){ frm.ary=[frm.t1_1,frm.t1_2,frm.t1_3];}
for (var zxc0=0;zxc0<frm.ary.length;zxc0+=3)
{
var total =1;
if (frm.ary[zxc0].value.length>0&&!isNaN(frm.ary[zxc0].value))
{
total =frm.ary[zxc0].value*1* frm.ary[zxc0+1].value;
}
frm.ary[zxc0+2].value =total;
}
var sum1 =0;
for (var zxd0=0;zxd0<frm.ary.length;zxd0+=3)
{
if (frm.ary[zxd0+2].value.length>0&&!isNaN(frm.ary[zxd0+2].value))
{
sum1 +=parseInt(frm.ary[zxd0+2].value);
}
}
frm.sum.value = sum1;
}
</script>
<form action="final.php" method="post" name="form2" id="form2">
<imput type ="text" name ="temp" id="temp" >
<table border="2" border-color="#000000" border-type="solid" id="tblSample"
align="center" font-size="20">
<tr>
<th>
<input type="button" value="Add " onclick="addRowToTable();"></th><th>
<input type="button" value="Remove " onclick="removeRowFromTable();" /></th>
<th> <input type="button" value="Reset" onclick="formReset();">
</th>
</tr><br>
<tr id="cloneid" >
<td>
1.
</td>
<td>
<input type="text" name="t1_1" id="t1_1" size="16" value="0" onkeyup="Calc();"
onblur="Calc();">
</td>
<td>
<input type="text" name="t1_2" id="t1_2" size="16" value="0" onkeyup="Calc();"
onblur="Calc();">
</td>
<td>
<input type="text" name="t1_3" id="t1_3" value= "0" size="16">
</td>
</tr>
</table>
<table border="2" border-color="#000000" align="center">
<tr>
<td colspan="3" align="center">
Sum: <input type="text" name="sum" id="sum">
</td>
</tr>
</table>
</form>
<input type="button" name = "mybutton" id ="mybutton" value="set"
onclick="somefunction();">
}
and
form1 is same as mentioned including jquery for datetimepickers along witha couple of text boxes...
u can use Java Script
function button1click() {
yourForm.action = "Final.php";
yourForm.submit();
}
n in HTML
<form action='' method='post'>
..
</form>

Categories