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.
Related
This question already has answers here:
How to prevent form from being submitted?
(11 answers)
Closed 3 months ago.
I want to create a page that displays a message when the user gives input. But the moment I click on the button to display the message the page instantly reloads and clears out the page:
HTML Code:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
</head>
<body>
<form onsubmit="return getFibonacci()">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
<script src="script.js"></script>
</body>
</html>
JavaScript Code:
function getFibonacci() {
try {
var num = document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
}
catch (err) {
document.getElementById("result").innerHTML = err;
}
}
Prevent that by adding event.preventDefault. Also you need to convert the value of the input to number which is done by adding unary operator +document.getElementById("fibo").value;. You can also use parseInt
function getFibonacci(event) {
event.preventDefault()
try {
var num = +document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
} catch (err) {
document.getElementById("result").innerHTML = err;
}
}
<form onsubmit="return getFibonacci(event)">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
It is reloading because the default behaviour of submit handlers is to reload the page. To avoid this we have stop this by using event.preventDefault().
Try the below changes:
<!DOCTYPE html>
<html lang="en">
<head>
<title>Fibonacci Series</title>
</head>
<body>
<form onsubmit="return getFibonacci(event)">
<table>
<tr>
<td>Enter the number to get a fibonacci</td>
<td><input type="number" id="fibo" name="fibo" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" id="fibobtn" name="fibobtn" value="Get Fibonacci" /></td>
</tr>
</table>
<div id="result"></div>
</form>
<script src="script.js"></script>
</body>
</html>
function getFibonacci(event) {
event.preventDefault()
try {
var num = document.getElementById("fibo").value;
var fib0 = 0;
var fib1 = 1;
var next;
const fib = [];
for (var i = 0; i < num - 1; i++) {
next = fib0 + fib1;
fib0 = fib1;
fib1 = next;
fib.push(fib0)
document.getElementById("result").innerHTML = fib;
}
}
catch (err) {
document.getElementById("result").innerHTML = err;
}
}
I need to make a little site that get some text boxes, ('Codigo' 'Nome' 'Documento') put on a array, that I already did, and make a a function with ForEach to create only one <tr> to three <td> I'm just not understand what I'm doing bad
function atualizarTabela() {
var tabelaBody = document.getElementById("corpo-tabela"); // corpo-tabela = tbody I need to clean it first
tabelaBody.innerHTML = "";
registros.forEach(function (registros) { // registros is my array that content the three text boxes
var createTr = document.createElement('tr');
for (var i = 0; i < registros[i]; i++) {
var createTd = document.createElement("td");
createTd.textContent = registro[i];
createTr.appendChild(createTd);
}
});
};
<body>
<table id="clientes">
<thead>
<tr>
<th>Codigo</th>
<th>Nome</th>
<th>Documento</th>
</tr>
</thead>
<tbody id="corpo-tabela">
</tbody>
</table>
<div id="bloco-dados">
<p>Código</p>
<input type="text" id="txtCodigo" name="Código">
<p>Nome</p>
<input type="text" id="txtNome" name="Nome">
<p>Documento</p>
<input type="text" id="txtDocumento" name="Documento"><br>
<input type="button" name="botao" id="btnSalvar" value="Salvar"><br>
<input type="button" name="botao2" id="btnNovo" value="Novo">
</div>
<script src="script.js" type="text/javascript"></script>
</body>
Thank you :)
Try removing the white space between function and the argument, and changing the argument to a dummy variable. So
registros.forEach(function(r) {
var createTr = document.createElement('tr');
for (var i = 0; i < r.length; i++) {
let createTd = document.createElement("td");
createTd.textContent = r[i];
createTr.appendChild(createTd);
tabelaBody.appendChild(createTr);
}
});
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="utf-8">
<title>a1</title>
<link rel="stylesheet" href="a1.css" />
<script src="a1.js"></script>
</head>
<body>
<form id = "gallary" method="get" action="">
<div id="searchBox">
<input type="text" id="searchBar" placeholder="Search titles" />
<input type="submit" id="searchBtn" value="search" onclick="searchFunction()"/>
<select name="genre" id ="filterBar">
<option>Genre</option>
<option>Baroque</option>
<option>Mannerism</option>
<option>Neo-classicism</option>
<option>Realisim</option>
<option>Romanticism</option>
</select>
<input type="submit" id = "filterBtn" value="filter" onclick =
"filterFunction()" />
</div>
</form>
<div id="artistBox">
<table>
<caption>Paintings</caption>
<thead>
<tr>
<th></th>
<th>Title</th>
<th>Artist</th>
<th>Year</th>
<th>Genre</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="05030.jpg"/></td>
<td>Death of Marat</td>
<td>David, Jacques-Louis</td>
<td>1793</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="120010.jpg"/></td>
<td>Potrait of Eleanor of Toledo</td>
<td>Bronzino, Agnolo</td>
<td>1545</td>
<td>Mannerism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="07020.jpg"/></td>
<td>Liberty leading the people</td>
<td>Delacroix, Eugene</td>
<td>1830</td>
<td>Romanticism</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="13030.jpg"/></td>
<td>Arrangement in Grey and Black</td>
<td>Whistler, James Abbott</td>
<td>1871</td>
<td>Realisim</td>
</tr>
<tr>
<td><input type="checkbox" name="paintingname" /><img
src="06010.jpg"/></td>
<td>Mademoiselle Caroline Riviere</td>
<td>Ingres, Jean-Auguste</td>
<td>1806</td>
<td>Neo-classicism</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>
enter code here
above is my HTML code.
the searchBar is for searcing titles(the second column of tbody), the filter is for filtering genres(the fourth column of tbody).
I want to search and filter some specific content form the table and use on-click to trigger my functions but it didn't work. Can anyone help me?
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementByTagName("tr");
var td;
var filter = document.getElementById("filterBar").value;
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[1];
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
}
You are setting the values of 'input', 'tbody','tr', and 'td' at the start of the script. These get evaluated when the script is loaded but destroyed when the the script file is finished loading. That is the "searchFunction" does not know about the values of these tags.
Consider the updated code: (see it in action at: Plunker)
<script type="text/javascript">
function makeGreen(inputDiv){
inputDiv.style.backgroundColor = "green";
}
function searchFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
console.log(input);
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[1];
var filter = document.getElementById("filterBar").value;
if(td.innerHTML.toUpperCase() == input){
makeGreen(tr[i]);
}
};
}
function filterFunction(){
var input = document.getElementById("searchBar").value.toUpperCase();
var tbody = document.getElementById("tbody");
var tr = tbody.getElementsByTagName("tr");
for (var i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[4];
if(td.innerHTML == input){
tr[i].style.display = "";
}else{
tr[i].style.display = "none";
}
} // <-- Missing
}
</script>
I'm trying to create a Javascript if/then statement that goes along the lines of: if all of the checkboxes are checked then show this image, else show this other image. I'm completly stuck and not sure what to do...
<head>
<center>
<FONT FACE="LYDIAN,COMIC SANS MS,ARIAL" COLOR="#BDF6F4" SIZE="6"><MARQUEE LOOP="N"|"INFINITE" BGCOLOR="#E0BDF6" WIDTH="68%" HEIGHT="60" ALIGN="MIDDLE" HSPACE="4%" VSPACE="25">My To-Do List: Just Do It!</MARQUEE></FONT>
<p>
<span style="color:#937AF0">
Put 'To-Do' tasks in order according to priority, to add a new task simply click the add button. When task on list is completed, check done!
</p>
</center>
<style>
table, th, td
{
border: 1px solid black;
}
</style>
</head>
<body>
<body style="background:#E6E6FA">
<center>
<table id="specialtable">
<table style="background:#BDF6F4">
<tr>
<th> Done</th>
<th>Priority</th>
<th>Task</th>
</tr>
<tr>
<td><input type="checkbox"</td>
<td>1<br></td>
<td><input type="text"></td>
<td><button onclick="addRow(this);">Add</button><br></td>
</tr>
</table>
</center>
<script type = "text/javascript">
function addRow(e)
{
var current = e.parentNode.parentNode; // <tr>...</tr>
var tnew = current.cloneNode(true);
var rowCount = current.parentNode.getElementsByTagName("tr").length;
tnew.getElementsByTagName("td")[1].textContent = rowCount;
current.parentNode.appendChild(tnew);
}
</script>
</head>
<body>
You could code:
var thisImage = document.getElementById('thisImage'),
thatImage = document.getElementById('thatImage'),
checkboxes = document.querySelectorAll('input[type=checkbox]'),
cLen = checkboxes.length;
function changeHandler() {
// compare the length of the checkboxes
// with the length of checked ones
var allChecked = Array.prototype.filter.call(checkboxes, function(e) {
return e.checked;
}).length === cLen;
if (allChecked) {
thisImage.style.display = 'block';
thatImage.style.display = 'none';
} else {
thisImage.style.display = 'none';
thatImage.style.display = 'block';
}
}
Array.prototype.forEach.call(checkboxes, function (e) {
e.addEventListener('change', changeHandler, false);
});
Refer this:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script>
function count(obj){
var x = document.getElementsByTagName("INPUT");
var y = [];
for (var cnt = 0; cnt < x.length; cnt++) {
if (x[cnt].type == "checkbox") y.push(x[cnt]);
}
var chkboxCount = y.length;
var cnt = 0;
for(var i=1; i<=chkboxCount; i++){
var checkbox = 'chk' + i;
if(document.getElementById(checkbox).checked){
cnt++;
}
}
if(cnt == 3){
document.getElementById('pic').innerHTML = '<img src = "img_flwr.gif">';
} else{
document.getElementById('pic').innerHTML = '<img src = "img_tree.gif">';
}
}
</script>
<input type="checkbox" name="chk1" id="chk1" onclick="count(this)">
<input type="checkbox" name="chk2" id="chk2" onclick="count(this)">
<input type="checkbox" name="chk3" id="chk3" onclick="count(this)">
<br>
<div id="pic"></div>
</body>
</html>
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
:)