How to add data to table on click of button using Javascript - javascript

<html>
<head>
<style type="text/css">
table, th, td {
position: relative;
border: 1px solid black;
width: 40%;
height:40px;
top: 5%;
}
</style>
<script type="text/javascript">
function lab()
{
var x= document.getElementById('lab').value;
var rows="";
rows+= "<tr><td>"+x+"</td></tr>";
}
function inp()
{
var y= document.getElementById('inp1').value;
}
</script>
</head>
<body>
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td></td>
<td></td>
</tr>
<tbody></tbody>
</table>
</html>
I am trying to add the text in the column of the table on the click of the button.
so please help me to add the text written on the button in the column of the table
thank you

I don't understand your requirement completely, but you can use innerHTML to wipe out earlier contents and insert new. Or use appendChild and createElement to make and insert new elements on the go. The example demonstrates both with each button.
function lab() {
var x = document.getElementById('lab').value;
var rows = "";
rows += "<tbody><tr><td>" + x + "</td></tr></tbody>";
document.getElementById('me1').innerHTML = rows;
}
function inp() {
var table = document.getElementById('me1');
var tbody = table.getElementsByTagName('tbody')[0];
var y = document.getElementById('inp1').value;
var text = document.createTextNode(y);
var col = document.createElement('td');
var row = document.createElement('tr');
col.appendChild(text);
row.appendChild(col);
tbody.appendChild(row);
}
table,
th,
td {
position: relative;
border: 1px solid black;
width: 40%;
height: 40px;
top: 5%;
}
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td></td>
<td></td>
</tr>
<tbody></tbody>
</table>

I have been also trying out how to input values into HTML table with the click of a button, and I found out this simple way by just using innerHTML and the id of the td tag. I have reformatted your code, hope this would be useful.
<!DOCTYPE html>
<head>
<style type="text/css">
table, th, td {
position: relative;
border: 1px solid black;
width: 40%;
height:40px;
top: 5%;
}
</style>
<script type="text/javascript">
function lab()
{
var x= document.getElementById('lab').value;
document.getElementById('00').innerHTML=x;
}
function inp()
{
var y= document.getElementById('inp1').value;
document.getElementById('01').innerHTML=y;
}
</script>
</head>
<body>
<button id="lab" onclick="lab()" value="label">Label</button>
<button id="inp1" onclick="inp()" value="Input">Input</button>
<button id="res" onclick="reset()">reset</button>
</body>
<table id="me1">
<tr>
<td id='00'></td>
<td id='01'></td>
</tr>
<tbody></tbody>
</table>
</html>

Related

Why button doesn't append row to table? [duplicate]

This question already has answers here:
How can I apply a jQuery function to all elements with the same ID?
(4 answers)
Event binding on dynamically created elements?
(23 answers)
Closed 1 year ago.
Sup! My code dynamically creates tables by clicking div, but it appends row only to first one. All tables are stored in div, containing the table itself and div with the row adding button, which is contained in the main div.
HTML
<div id="main-container">
<div id="container">
<table id="table" class="my-table">
<tr>
<th>X</th>
<th>Y</th>
</tr>
<tr>
<td class="xcell" contenteditable="true"></td>
<td class="ycell" contenteditable="true"></td>
</tr>
<tr>
<td class="xcell" contenteditable="true"></td>
<td class="ycell" contenteditable="true"></td>
</tr>
<tr>
<td class="xcell" contenteditable="true"></td>
<td class="ycell" contenteditable="true"></td>
</tr>
<tr>
<td class="xcell" contenteditable="true"></td>
<td class="ycell" contenteditable="true"></td>
</tr>
</table>
<div id="addRowChild" class="add"><b>+</b></div>
</div>
</div>
</div>
In my JS code, I've been trying to get tables from each container div with siblings() method, but it doesn't work and I have no idea why it happens.
JS
function createNewTable() {
let newTable = document.createElement("table")
let mainContainer = document.getElementById("main-container") //refers to the div, containing all tables
let containerDiv = document.createElement("div") //creates div, which contains table and row adding div
let addRowButton = document.createElement("div") //creates row adding button
mainContainer.append(containerDiv)
containerDiv.id = "container"
containerDiv.append(newTable)
newTable.className = "my-table"
newTable.id = "table"
$("#addRowChild").click(function() {
let table = $("#addRowChild").siblings(".my-table")
table.append(`<tr><td class = "xcell" contenteditable = "true"></td><td class = "ycell" contenteditable = "true"></td></tr>`);
});
The script was not working because it nested the click event handler method and the createNewTable() method. Application screenshot and test code are available below:
function createNewTable()
{
let newTable = document.createElement("table")
let mainContainer = document.getElementById("main-container") //refers to the div, containing all tables
let containerDiv = document.createElement("div") //creates div, which contains table and row adding div
let addRowButton = document.createElement("div") //creates row adding button
mainContainer.append(containerDiv);
containerDiv.id = "container";
containerDiv.append(newTable);
newTable.className = "my-table";
newTable.id = "table";
}
$("#addRowChild").click(function() {
var markup = `
<tr>
<td class = "xcell" contenteditable="true">####</td>
<td class = "ycell" contenteditable="true">####</td>
</tr>
`;
let table = $("table tbody");
table.append(markup);
});
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
.block {
display: block;
width: 100%;
border: none;
background-color: #04AA6D;
padding: 14px 28px;
font-size: 16px;
cursor: pointer;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<title>Document</title>
</head>
<body>
<div id="main-container">
<div id="container">
<table id="table" class="my-table">
<thead>
<tr>
<th>X</th>
<th>Y</th>
</tr>
</thead>
<tbody>
<tr>
<td class="xcell" contenteditable="true">1</td>
<td class="ycell" contenteditable="true">2</td>
</tr>
</tbody>
</table>
<button style="margin-top: 25px;" class="block" id="addRowChild" class="add"><b>+</b></button>
</div>
</div>
</body>
</html>

How to hide the table when i click button using js?

First of all the view page shows only two buttons leave and attendance.
when i click the leave button i shows the table(tb2).and again i click the that button it hide the table
When i click the attendance i display the another table(tb3).it is same as previous
Now for me i want when i click the leave button the opened attendance table should be closed and it same for the attendance button.
My code:
var click = document.getElementById('clickme');
click.addEventListener('click', myfunction);
function myfunction() {
var tablewrap = document.getElementById('tb2');
tablewrap.classList.toggle('show')
};
var click = document.getElementById('click');
click.addEventListener('click', myfunction);
function myfunction() {
var tablewrap = document.getElementById('tb3');
tablewrap.classList.toggle('show')
};
var click = document.getElementById('clickme');
click.addEventListener('click', myfunction);
function myfunction() {
var tablewrap = document.getElementById('tb2');
tablewrap.classList.toggle('show');
document.getElementById('tb3').classList.remove('show');
};
var click = document.getElementById('click');
click.addEventListener('click', myfunction);
function myfunction() {
var tablewrap = document.getElementById('tb3');
tablewrap.classList.toggle('show');
document.getElementById('tb2').classList.remove('show')
};
Remove the classes explicitly
Use JQuery it will make things easy.
$('#btnLeave').click(function(){
if($('#tblLeave').css('display')=='none'){
$('#tblLeave').css('display','block');
} else {
$('#tblLeave').css('display','none');
}
});
$('#btnAttendance').click(function(){
if($('#tblAttendance').css('display')=='none'){
$('#tblAttendance').css('display','block');
} else {
$('#tblAttendance').css('display','none');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnLeave">Leave</button>
<button id="btnAttendance">Attendance</button>
<br><br>
<table id="tblLeave" style="border: 1px solid; width: 100%; display: none">
<thead>
<td>Leave<td>
</thead>
<table>
<br>
<table id="tblAttendance" style="border: 1px solid; width: 100%; display: none">
<thead>
<td>Attendance<td>
</thead>
<table>
Or Alternating the show and hide of two tables
$('#btnLeave').click(function(){
if($('#divLeave').css('display')=='none'){
$('#divLeave').css('display','block');
$('#divAttendance').css('display','none');
}
});
$('#btnAttendance').click(function(){
if($('#divAttendance').css('display')=='none'){
$('#divAttendance').css('display','block');
$('#divLeave').css('display','none');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="btnLeave">Leave</button>
<button id="btnAttendance">Attendance</button>
<br><br>
<div id="divLeave">
<table id="tblLeave" style="border: 1px solid; width: 100%;">
<thead>
<td>Leave<td>
</thead>
</table>
</div>
<br>
<div id="divAttendance" style="display: none; position: absolute; top: 47px; width: 100%">
<table id="tblAttendance" style="border: 1px solid; width: 100%">
<thead>
<td>Attendance<td>
</thead>
</table>
</div>

auto refrsh api data

i need to refresh particular data line in every interval when the value change
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()+ randomnumber);
}, 1000);
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
document.getElementById('output').innerHTML=data;
})
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<body>
<div id="output" style="margin:5px 0;">
</div>
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
</body></html>
Here i get all refreshed in every seconds. i need to refresh only a particular line
Hi Here I done as per your req, Just one line I have done, for other line do by your self, I just makes your string obj into obj and added table style.
js fiddle
html
<style>
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 100%;
}
td, th {
border: 1px solid #dddddd;
text-align: left;
padding: 8px;
}
tr:nth-child(even) {
background-color: #dddddd;
}
</style>
<div id="output" style="margin:5px 0;">
</div>
<table>
<tr>
<th style="margin-left:20px">exchange</th>
<th>fromSymbol</th>
<th>toSymbol</th>
<th> volume24h</th>
<th>volume24hTo</th>
</tr>
<tr>
<td>Bitfinex</td>
<td>BTC</td>
<td>USD</td>
<td id="volume24h">BTC</td>
<td id="volume24hTo">USD</td>
</tr>
</table>
java script
$(document).ready(
function() {
setInterval(function() {
var randomnumber = Math.floor();
$('#output').text(
gettxt()) + randomnumber;
}, 1000);
gettxt()
});
function gettxt(){
fetch('https://min-api.cryptocompare.com/data/top/exchanges?fsym=BTC&tsym=USD')
.then((res)=>res.text())
.then((data)=>{
var dataTemp = JSON.parse(data);
document.getElementById('volume24h').innerHTML=dataTemp.Data[0].volume24h;
document.getElementById('volume24hTo').innerHTML=dataTemp.Data[0].volume24hTo;
console.log(dataTemp);
})
}

Random Color for <tr>

So overall I am trying to make the boxes change color when someone puts a mouse over them. Color has to be random. I know I am missing a connection point between my functions but I cant figure out what it is.
<!DOCTYPE html>
<html onmousedown='event.preventDefault();'
onmouseenter = "colorize();"
>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
Create a function called colorize that is passed an element object as its
parameter and sets the elements background color style property using the
rgb(r,g,b) method setting each r,g and b to a random number between 0 and
255.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function colorize(co) {
document.body.style.background = co;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
Use document.write() and for-loops to fill in the table to create a 16x16 box table. For each td element, create a onmouseenter call to colorize, passing it the element itself (this).
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
I'm not sure what you wanted to do with body background, nothing said about that in your text. ALos your colorizer func is overwritten. maybe you wanted something like this... ?
<!DOCTYPE html>
<html>
<head>
<title> Boxes </title>
<meta charset='utf-8'>
<style>
table {
border-spacing: 6px;
border: 1px rgb(#CCC);
margin-top: .5in;
margin-left: 1in;
}
td {
width: 40px; height: 40px;
border: 1px solid black;
cursor: pointer;
}
</style>
<script>
function colorize(el) {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
el.style.backgroundColor = '#' +r+g+b;
}
</script>
</head>
<body>
<table>
<tbody>
<script type="text/javascript">
var row = 16;
var cols = 16;
for(var r=0;r<row;r++){
document.write("</tr>");
for(var c=0;c<cols;c++){
document.write("<td onMouseEnter='colorize(this);'></td>");
}
document.write("</tr>");
}
</script>
</tbody>
</table>
</body>
</html>
You need to have your colorize function update each cell in your table. Replace both colorize() and colorize(co) with one function:
function colorize() {
var r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
for (var i = 0; i < document.getElementsByTagName("td").length; i++){
document.getElementsByTagName("td")[i].style.backgroundColor = "#"+r+g+b;
}
}
i play with Ids and adding onmousedown in html tag that calls the func.
function colorize() {
var
r = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
g = ('0'+(Math.random()*255|0).toString(16)).slice(-2),
b = ('0'+(Math.random()*255|0).toString(16)).slice(-2);
return '#' +r+g+b;
}
function change(){
var x = document.getElementById("1");
var y = document.getElementById("2");
x.style.color = colorize();
y.style.color = colorize();
}
<table frame="box" onmousedown="change()"id="1" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>January</td>
<td>$100</td>
</tr>
</table>
<table frame="box" onmousedown="change()" id="2" >
<tr>
<th>Month</th>
<th>Savings</th>
</tr>
<tr>
<td>February</td>
<td>$200</td>
</tr>
</table>

Table column re-sizing using jQuery

I am trying to write a piece of code that enables column re-sizing functionality to my data table.But its not working properly.. I explored on internet for couple of days but I could find nothing except some plug-ins. But I don't want to use any plug-in, since my data table is very complicated and if I use them the other functionalities of the table may be destroyed.Thus I tried to write my own. Can you please check and refine my code or suggest any other code that fulfills my spec....
Note: User can re-size the column towards right upto table width but towrds left, its upto td's left position only..
Eidt: Maxwell has given a great alternative..It works fine but in one case.If I try to resize towards left side, its not allowing since td width is fixed to it's content width...But I want to re-size it to left side upto it's its offset().left value by putting td's style to overflow:hidden or some other way....
Here is my piece of code....
<!DOCTYPE HTML PUBLIC>
<html>
<head>
<title> New Document </title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<style>
table{
border-collapse:collapse;
}
table td{
border:1px solid red;
}
.vUiDtColResize{
width:2px;
height:20px;
border:1px solid blue;
float:right;
display:block;
cursor:w-resize;
position:relative;
right:-3px;
float:top;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<td>S.No <div class="vUiDtColResize"></div></td>
<td>Name <div class="vUiDtColResize"></div></td>
<td>Qualif <div class="vUiDtColResize"></div></td>
</tr>
</thead>
<tbody>
<tr> <td>1</td><td>Rama Rao</td><td>M.C.A</td></tr>
<tr> <td>2</td><td>Dushyanth</td><td>B.Tech</td></tr>
<tr> <td>3</td><td>AnandKumar</td><td>M.C.A</td></tr>
<tr> <td>4</td><td>Veera Reddy</td><td>B.Tech</td></tr>
</tbody>
</table>
<div id="helper"></div>
</body>
<script>
$('.vUiDtColResize').each(function(){
var _rsTd = $(this).parent('td');
var _rsTr = _rsTd.parent('tr');
var _rsTdRight,_thisLeft,_rsTdWidth;
$(this).draggable({axis:'x',containment:_rsTd,refreshPositions:true,
create:function(event,ui){
},
start:function(event,ui){
_rsTdRight = _rsTd.offset().left + _rsTd.outerWidth();
},
drag:function(event,ui){
var _sizeDiff = $(this).offset().left - _rsTdRight;
_rsTdRight = $(this).offset().left;
_rsTdWidth = _rsTd.outerWidth() + _sizeDiff;
_rsTd.outerWidth(_rsTdWidth);
},
stop:function(event,ui){
}
});
});
</script>
</html>
I merged your code with some techniques that I found — http://jsfiddle.net/tpqn7/
IMHO, there are still some problems. First of all I suppose it's would be better (also easier) if table headers can be re-sized by pressing each TH, no only small border.
Hope this helps.
After had been exploring in internet for couple of days, I got a good code,which was modified by me to make it satisfies my requirement as well( Of course, my change is bit little.It might be useful to somebody else,so I am posting here...
style
<link rel="stylesheet" href="E:\Examples\BSP\BSPExtensions\jquery-ui-1.8.18.custom.css"/>
<style>
table {
table-layout: fixed;
border-collapse: collapse;
border: 1px solid black;
}
tr.last td {
border-bottom: 1px solid black;
}
td {
border-right: 1px solid black;
border-bottom: 1px solid black;
position: relative;
white-space:nowrap;
padding: 2px 5px;
text-align: left;
overflow:hidden;
}
td.last {
border-right: none;
}
thead td div:first-child{
text-overflow:ellipsis;
overflow:hidden;
}
tbody td div:first-child{
overflow:hidden;
}
.scrollContainer {
overflow:auto;
width:700px;
height:auto;
display:inline-block;
border:1px solid red;
}
#-moz-document url-prefix() {
.resizeHelper,.ui-resizable-e {
position: relative;
float: right;
}
}
</style>
Script
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/jquery-ui.js"></script>
<script>
/**
* Enables resizable data table columns.
**/
(function($) {
$.widget("ih.resizableColumns", {
_create: function() {
this._initResizable();
},
_initResizable: function() {
var colElement, colWidth, originalSize;
var table = this.element;
this.element.find("thead td").resizable({
handles: {"e": ".resizeHelper"},
minWidth: 2, // default min width in case there is no label
// set correct COL element and original size
start:function(event, ui) {
var colIndex = ui.helper.index() + 1;
colElement = table.find("thead > tr > td.ui-resizable:nth-child(" + colIndex + ")");
colWidth = parseInt(colElement.get(0).style.width, 10); // faster than width
originalSize = ui.size.width;
},
// set COL width
resize: function(event, ui) {
var resizeDelta = ui.size.width - originalSize;
var newColWidth = colWidth + resizeDelta;
colElement.width(newColWidth);
// height must be set in order to prevent IE9 to set wrong height
$(this).css("height", "auto");
}
});
}
});
// init resizable
$("#MyTable").resizableColumns();
})(jQuery);
</script>
Your html is to be like:*
<div class="scrollContainer">
<table class="resizable" id="MyTable" width="100%">
<thead>
<tr>
<td class="ui-resizable" style="width:100px;">
<div>
<span >Column 1</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
<td class="ui-resizable" style="width:200px;">
<div>
<span >Column 2</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
<td class="ui-resizable" style="width:300px;">
<div>
<span >Column 3</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
<td class="ui-resizable" style="width:150px;">
<div>
<span >Column 4</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
<td class="ui-resizable" style="width:200px;">
<div>
<span >Column 5</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
<td class="ui-resizable last" style="width:100px;">
<div>
<span >Column 6</span>
<div class="resizeHelper ui-resizable-handle ui-resizable-e"></div>
</div>
</td>
</tr>
</thead>
<tbody>
<tr><td><div>Column 1</div></td><td><div>Column 2</div></td>
<td><div>Column 3</div></td><td><div>Column 4</div></td>
<td><div>Column 5</div></td><td><div>Column 6</div></td>
</tr>
<tr class="last">
<td><div>Column 1</div></td><td><div>Column 2</div></td>
<td><div>Column 3</div></td><td><div>Column 4</div></td>
<td><div>Column 5</div></td><td><div>Column 6</div></td>
</tr>
</tbody>
</table>
</div>

Categories