Wrote javascript to dynamically create table. Need help validating user input - javascript

I already have a table being created in javascript. It is based off user input and will check to make sure the value entered is a number. But how do I ALSO make it check to make sure the values entered are
higher then 0
and less then 10
<html>
<head>
<title>Homework 1</title>
<script language="javascript" type="text/javascript">
function doWork(){
var rows = document.getElementById("input1").value;
var columns = document.getElementById("input2").value;
//alert(rows);
//alert(columns);
if(isNaN(rows) == true || isNaN(columns) == true){
document.getElementById('tablePlacement').innerHTML = "Input must be integer";
}
else{
var htmlInput = "";
htmlInput += "<table border='1'>";
htmlInput += "<tr>";
//Column Headers
for (i = 0; i <= columns; i++){
htmlInput += ("<td><b>" + i + "</b></td>");
}
htmlInput += "</tr>";
for (i = 1; i <= rows; i++){
htmlInput += ("</br><tr><td><b>" + i + "</b></td>");
for (j = 1; j<= columns; j++){
var multiplyResult = i * j;
htmlInput += ("<td>" + multiplyResult + "</td>");
}
htmlInput += "</tr>";
}
htmlInput += "</table>";
document.getElementById('tablePlacement').innerHTML = htmlInput;
}
};
</script>
</head>
<body>
<form id="input1Form">
Rows: <input type="text" id="input1">
</form>
<form id="input2Form">
Columns: <input type="text" id="input2">
</form>
<button type="button" onclick="doWork()">Enter</button>
<div id="tablePlacement">
</div>
</body>

if(rows <=0 || rows >= 10){
document.getElementById('tablePlacement').innerHTML = "Input rows must be between 1 and 9";
}
if(cols <=0 || cols >= 10){
document.getElementById('tablePlacement').innerHTML = "Input cols must be between 1 and 9";
}

Related

I want to prevent user from entering a duplicate value in array [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
full:
https://onlinegdb.com/HJN6CGLTD
I need help in here : want a code that check input1 and see if its already in array or not if it is error if not push it in array.
function AddPoints()
{
var item = document.getElementById("input1").value;
if (points.includes(item) === false) points.push(parseInt( item )); // duplicate check
else document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
displayPoints();
}
if i understand your question you can try this code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>
JS:
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
// I check if the item is a integer number
if(Number.isInteger(item)){
//when the item's value is not present in the array
if (points.includes(item,0) === false) {
points.push( item ); // new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
this is a test with the code
var i;
var points=[];
function AddPoints(){
var item = document.getElementById("input1").value;
item=parseInt(item);//only integer number
if(Number.isInteger(item)){
if (points.includes(item,0) === false) {
points.push( item );// new value
document.getElementById("demo2").innerHTML = "" ;
//displayPoints();
}
else {
document.getElementById("demo2").innerHTML = "The number Exist" ; // duplicate error
//displayPoints();
}
}
else{
document.getElementById("demo2").innerHTML = "The number error" ; // It is not a number
}
displayPoints();
}
function displayPoints(){
var i;
text = "<table border=1>";
for (i = 0; i < points.length; i++) {
text += "<tr>";
text += "<td>" + (i+1) + "</td>";
text += "<td>" + points[i] + "</td>";
text += "</tr>"
}
text += "<table>";
document.getElementById("demo").innerHTML = text;
}
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<script>
</script>
<body>
<label>input</label>
<input id="input1" type="text"/>
<input type="button" value="Add" onclick="AddPoints()"/>
<div id="demo"></div>
<div id="demo2"></div>
</body>
</html>

create calendar by javascript

I would like to create, tr, td through javascript, and make a simple calendar from day 1 to day 30.
I created an example with console.log() for trying to understand for myself.
When I tried to switch from console.log() to document.getlementById("calendar") for printing on html, it did not print.
The error showed that
calendar.js:3 Uncaught ReferenceError: Invalid left-hand side in
assignment
my understanding with console.log():
for (var i = 1; i <= 5; i++) {
//open tr tag
console.log("<tr>");
for(var i = 1; i <= 30; i++){
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
console.log(days);
//if i divide by 7 and remainder is 0
if(i % 7 == 0 || i == 31){
console.log("</tr>");
console.log("<tr>");
}
};
console.log("</tr>");
};
Actual my code with document.getElementById("calendar")
for (var i = 1; i <= 5; i++) {
//open tr tag
document.getElementById("calendar") += "<tr>";
for(var i = 1; i <= 30; i++){
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
document.getElementById("calendar") += days;
//if i divide by 7 and remainder is 0
if(i % 7 == 0 || i == 31){
document.getElementById("calendar") += "</tr>";
document.getElementById("calendar") += "<tr>";
}
};
document.getElementById("calendar") += "</tr>";
};
my index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<div >
<table>
<tr>
<th>S</th>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</tr>
<span id="calendar">
</span>
</table>
</div>
<script src="js/calendar.js" ></script>
</body>
</html>
The error showed that
Uncaught ReferenceError: Invalid left-hand side in assignment
First, you can't have a <span> inside your table where you placed it. A table can only hav a <tr> at this place. But you don't need this span at all, you can just append the string direcly to the table, so I moved the ID to the <table>-tag.
I also used a variable to build all the HTML and after it's all built I inserted it with insertAdjacentHTML() at the end of the table.
var table = document.getElementById("calendar");
var htmlstring = "";
for (var i = 1; i <= 5; i++) {
//open tr tag
htmlstring += "<tr>";
for (var i = 1; i <= 30; i++) {
var days = "<td>" + i + "</td>";
//print 1 to 31 with td tag
htmlstring += days;
//if i divide by 7 and remainder is 0
if (i % 7 == 0 || i == 31) {
htmlstring += "</tr>";
htmlstring += "<tr>";
}
};
htmlstring += "</tr>";
};
//console.log(htmlstring);
table.insertAdjacentHTML('beforeend', htmlstring)
<div>
<table id="calendar">
<tr>
<th>S</th>
<th>M</th>
<th>T</th>
<th>W</th>
<th>T</th>
<th>F</th>
<th>S</th>
</tr>
</table>
</div>

Javascript getting total sum from wrong checkbox trigger

Below are two different checkbox and the javascript below seems to be trigger by termsChkbx checkbox instead of chosen. How do I change this portion
var chosen = item.parentElement.querySelector('[type="checkbox"]'); ?
echo "\t<div class='item'>
<span class='CDTitle'>{$CD['CDTitle']}</span>
<span class='CDYear'>{$CD['CDYear']}</span>
<span class='catDesc'>{$CD['catDesc']}</span>
<span class='CDPrice'>{$CD['CDPrice']}</span>
<span class='chosen'><input type='checkbox' id='selectChkbx' name='CD[]' value='{$CD['CDID']}' title='{$CD['CDPrice']}' /></span>
</div>\n";
<p style="color: red; font-weight: bold;">I have read and agree to the terms and conditions
<input type="checkbox" id="termsChkbx" onchange="isChecked(this,'sub1')"/></p>
JS:
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("selectChkbx").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total;
}
createCheckbox();
You can try something like this:
JSFiddle
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>" + num + "<br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
total+=parseFloat(chk[i].value);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
<div id="content"></div>
<p id="total">0</p>
Edit 1
I believe reason why you are not getting value is because of element structure. You have a span tag which holds price and another span tag holds checkbox. For such structure, you will have to navigate to that span and fetch its value. Following is depicted below.
Fetching Span's value
var price = chk[i].parentNode.previousSibling.textContent;
Code
function createCheckbox(){
var html = "";
for(var i = 0; i<5; i++){
var num = (Math.random() * 10).toFixed(2);
html += "<span>" + num + "</span>";
html += "<span><input type='checkbox' class='chk' value='" +num+ "' onchange='updateTotal()'>Check</span><br/>";
}
document.getElementById("content").innerHTML = html;
}
function updateTotal(){
var chk = document.getElementsByClassName("chk");
var total = 0;
console.log(chk);
for(var i in chk){
if(chk[i].checked){
var price = chk[i].parentNode.previousSibling.textContent;
total += parseFloat(price);
}
}
document.getElementById("total").innerHTML = total.toFixed(2);
}
createCheckbox();
.chk{
}
<div id="content"></div>
<p id="total">0</p>

Dynamically creating an html table with Javascript

I am trying to create a table based on user input (actually two or three tables depending on the user input..) using Javascript, I am very much native to PHP and have already got this working in PHP, however i would like the user to be able to see the table before the query it. I found a script on here that partially did what I wanted and have attempted to edit it (I found it surprisingly similar to PHP) Basically it calculates the total amount of cells (ports) splits it by rows and columns, the "super" column is used if the user would like it to be split into multiple tables, which align next to each other, hence the div tag. Here's my JS:
<html>
<head>
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for(u=1; u<=num_row; u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
</head>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
Here is what the final output looks like after it has been processed by PHP (ports:24, col:6, rows:2, super:2):
Here is a js fiddle that I threw together:
http://jsfiddle.net/9SnLB/
Currently, when I click the button nothing happens, but, I suppose that is my first issue, but am I going about the setup correctly? Why wont the button run the function?
Two mistakes. One you didn't close the function bracket, ie a missing } at the end. The second is you used $row instead of the variable you created num_rows. For some reason it doesn't work in the fiddle, it does however work locally. The fiddle is saying the createTable function is undefined.
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for( var i=0; i<num_super; i++){
var theader = '<div><table border="1">\n';
for($u=1; $u<=num_rows; $u++){
tbody += '<tr>';
for( var j=0; j<colStart; j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>'
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
var table = [["a1","a2","a3"]["b1","b2","b3"]["c1","c2","c3"]];
for(x = table.length;x > 0;x--) {
document.write("<tr>");
for(y = table[x].length;y > 0;y--) {
document.write("<td>"+y+"</td>");
}
document.write("</tr>");
}
Sorry if the syntax is wrong. You get the idea.
You need to change your jsFiddle framework to "no wrap (head)" and correct errors in the javascript. "no wrap (head)" will allow access the function. The "for ($u=1" loop is missing the close brace and $row should be num_rows. The "for (j=0" loop is missing a semicolon at the last "tbody=".
here's the corrected js.
function createTable() {
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
for (var i = 0; i < num_super; i++) {
var theader = '<div><table border="1">\n';
for ($u = 1; $u <= num_rows; $u++) {
tbody += '<tr>';
for (var j = 0; j < colStart; j++) {
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}

Can't create 2 tables

I'm trying to dynamically create a table based on user input, and it's working perfectly, however, it is supposed to make a table based on the super input the user gives, so if super is 2, then it loops to create 2 tables. However it is doing everything but that, because if it was, then the tables would be next to each other, not one below each other as I have set the CSS that way. Any ideas?
<script type="text/javascript">
function createTable()
{
var num_ports = document.getElementById('ports').value;
var num_super = document.getElementById('super').value;
var num_rows = document.getElementById('rows').value;
var num_cols = document.getElementById('cols').value;
var tbody = '';
var colStart = num_cols / num_super;
var y = 1;
for( var i = 1; i <= num_super; i++){
var theader = '<div style="margin:0 auto;"><table border="1" style="border:1px solid black; float:left;">\n';
for(u = 1; u <= num_rows; u++){
tbody += '<tr>';
for( var j = 0; j < colStart; j++)
{
tbody += '<td style="width:80px; height:70px;">';
tbody += '<sub style="float:right; position:relative; top:24px; z-index:11; ">' + y + '</sub>';
tbody += '</td>';
y++;
}
tbody += '</tr>\n';
}
var tfooter = '</table></div>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
}
</script>
<body>
<form name="tablegen">
<label>Ports: <input type="text" name="ports" id="ports"/></label><br />
<label>Super Columns: <input type="text" name="super" id="super"/></label><br />
<label>Rows: <input type="text" name="rows" id="rows"/></label><br />
<label>Columns: <input type="text" name="cols" id="cols"/></label><br/>
<input name="generate" type="button" value="Create Table!" onclick='createTable();'/>
</form>
<div id="wrapper"></div>
</body>
</html>
How it should look
It resets the table it created to the new table in current iteration in this line:
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
You have to do something like this:
document.getElementById('wrapper').innerHTML += theader + tbody + tfooter;
In addition to your comment:
var colStart = num_cols / num_super;
Should mabe be:
var colStart = num_cols * num_super;

Categories