Changing JavaScript code to jQuery of my own script - javascript

I need a help on changing the JavaScript code to jQuery of my own code.
TASK:
When I click the '+' button on the tree, it shows/adds a new row to the table also the button changes to '-'(minus). After that, again I click on the minus(-) button, it hides the row.
The above task is done in javascript. I need to convert it to jQuery. Is it possible? If yes means, please help me. Thanks in advance.
The code is as follows:
<html>
<head>
<title>Appending table row in a table</title>
<script language = "javascript">
function changeImage(that,x)
{
var clickedrow = document.getElementById("append"+x);
var subrow = document.getElementById("append"+x+"a");
var table = document.getElementById("mytable");
if(that.src === "http://renko-server/sample/arun/jquery/images/plus.gif")
{
that.src = "http://renko-server/sample/arun/jquery/images/minus.gif";
if(subrow)
{
subrow.style.display="";
}
else
{
subrow = table.insertRow(clickedrow.rowIndex+1);
subrow.id="append"+x+"a";
var cell1 = subrow.insertCell(0);
var cell2 = subrow.insertCell(1);
var cell3 = subrow.insertCell(2);
cell1.innerHTML = "";
cell2.innerHTML = "Kumar";
cell3.innerHTML = "Madurai";
}
}
else
{
that.src = "http://renko-server/sample/arun/jquery/images/plus.gif";
subrow.style.display="none";
}
}
</script>
</head>
<body>
<table id="mytable" class="appendtable">
<tr><td></td><td><b>Name</b></td><td><b>Location</b></td></tr>
<tr id="append1"><td><img id="plus1" onclick="javascript:changeImage(this,1);" src="http://renko-server/sample/arun/jquery/images/plus.gif" / ></td><td>Arun</td><td>Sivakasi</td></tr>
<tr id="append2"><td><img onclick="javascript:changeImage(this,2);" id="plus2" src="http://renko-server/sample/arun/jquery/images/plus.gif"/></td><td>Raj</td><td>Kovai</td></tr>
<tr id="append3"><td><img id="plus3" src="http://renko-server/sample/arun/jquery/images/plus.gif" onclick="javascript:changeImage(this,3);"/></td><td>Jerome</td><td>Bangalore</td></tr>
</table>
</body>
</html>

change you html like this:-
<table id="mytable" class="appendtable">
<tr><td></td><td><b>Name</b></td><td><b>Location</b></td></tr>
<tr id="append1"><td><img id="plus1" onclick="changeImage(this);" src="http://renko-server/sample/arun/jquery/images/plus.gif" /> ></td><td>Arun</td><td>Sivakasi</td></tr>
// ^^^ this is change
<tr id="append2"><td><img onclick="changeImage(this);" id="plus2" src="http://renko-server/sample/arun/jquery/images/plus.gif" /></td><td>Raj</td><td>Kovai</td></tr>
<tr id="append3"><td><img id="plus3" src="http://renko-server/sample/arun/jquery/images/plus.gif" onclick="javascript:changeImage(this);" /></td><td>Jerome</td><td>Bangalore</td></tr>
</table>
and your jquery function is:-
function changeImage(that) {
var clickedrow = $(that);
var subrow = $('#' + clickedrow.attr('id') + 'a');
var table = $("#mytable");
if (clickedrow.attr('src') === "http://renko-server/sample/arun/jquery/images/plus.gif") {
clickedrow.attr('src', "http://renko-server/sample/arun/jquery/images/minus.gif");
if (subrow.length) {
subrow.show();
}
else {
subrow = $('<tr><td></td><td>Kumar</td><td>Madurai</td></tr>').insertAfter(clickedrow.parents('tr'));
}
}
else {
clickedrow.attr('src', "http://renko-server/sample/arun/jquery/images/plus.gif");
subrow.hide();
}
}
Demo
Or if you don't want to use onclick direct on image Try this

Related

How to add a row with data into html table using array, function partly working

I would appreciate the help. I am trying to add new rows into a html table, where on click button, it adds row at random. My add function is not able to add the data from the array to row but creates the rows.
HTML Code
<!DOCTYPE html>
<html>
<head>
<script src="./javascript1.js"></script>
</head>
<body>
<table id="member">
<tr>
<th>Name</th><th>Email</th><th>Remove</th>
</tr>
<tr>
<td>Iza K</td><td>iza#mail.com</td><td><button type="button" onclick="deleteRow(this)">Delete</button></td>
</tr>
<tr>
<td>Mima T</td><td>mimat#mail.com</td><td><button type="button" onclick="deleteRow(this)">Delete</button></td>
</tr>
</table>
<button type="button" onclick="addFunction()">Click Me!</button>
JavaScript Code
// function deleteRow(r) {
// var i = r.parentNode.parentNode.rowIndex;
// document.getElementById("member").deleteRow(i);
// }
}
var dataArray = [{
name: "Brandon I",
email: "b.i#mail.com",
remove: "<button type='button' onclick='deleteRow(this)'>Delete</button>"
}, {
name: "John Bishops",
email: "johnb#mail.com",
remove: "<button type='button' onclick='deleteRow(this)'>Delete</button>"
}];
// need to add to select user at random when clicked add button
const randomElement = dataArray[Math.floor(Math.random() * dataArray.length)];
function addFunction()
{
var table = document.getElementById('members');
for (var i = 0; i < dataArray.length; i++)
{
var row = table.insertRow(-1);
var name = row.insertCell(0);
var email = row.insertCell(1);
var remove = row.insertCell(2);
name.innerHTML = dataArry[0];
email.innerHTML = dataArray[0];
remove.innerHTML = dataArray[0];
}
}
First of all, u have typo on getElementById() void, it should be .member rather than .members. After your randomElement variable needs to be into your function, otherwise return value of this variable will be always the same. And finally, you can directly access your properties object dataArray thanks to randomElement variable in order to set your content.
Complete code :
let dataArray = [{
name: "Brandon I",
email: "b.i#mail.com",
remove: "<button type='button' onclick='deleteRow(this)'>Delete</button>"
}, {
name: "John Bishops",
email: "johnb#mail.com",
remove: "<button type='button' onclick='deleteRow(this)'>Delete</button>"
}];
function addFunction()
{
// need to add to select user at random when clicked add button
const randomElement = dataArray[Math.floor(Math.random() * dataArray.length)];
var table = document.getElementById('member');
var row = table.insertRow(-1);
var name = row.insertCell(0);
var email = row.insertCell(1);
var remove = row.insertCell(2);
name.innerHTML = randomElement.name;
email.innerHTML = randomElement.email;
remove.innerHTML = randomElement.remove;
}
<html>
<head>
</head>
<body>
<table id="member">
<tr>
<th>Name</th><th>Email</th><th>Remove</th>
</tr>
<tr>
<td>Iza K</td><td>iza#mail.com</td><td><button type="button" onclick="deleteRow(this)">Delete</button></td>
</tr>
<tr>
<td>Mima T</td><td>mimat#mail.com</td><td><button type="button" onclick="deleteRow(this)">Delete</button></td>
</tr>
</table>
<button type="button" onclick="addFunction()">Click Me!</button>
</body>
</html>

can't figure out why this doesn't add row and cell to table

When I run the script I don't get any errors in the console, it just won't add a row and cell. I need to add a row and cell when more than one row of results are found. Do I have errors???? This is a small bit of the code
var txt = "";
var i = 0;
for (state in stateMiles) {
i++;
var x =(stateMiles[state]);
(stateMiles[state])= parseFloat(x);
function appendRow() {
var tbl = document.getElementById("table"), // table reference
row = tbl.insertRow(tbl.rows.length), // append table row
i;
// insert table cells to the new row
for (i = 0; i < tbl.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'row');
}
}
$("#results").append
$(".state" + i).append(state);
$(".mile" + i).append(stateMiles[state]);
}
Your code snippet is a mess. Are you declaring a function inside a for loop?
Don't do that.
This is the kind of thing that MVC style libraries like Angular, React, etc all really excel at, but if you're looking to do this, here's some code that should help.
<script type="text/javascript">
$(function() {
var stateMiles = [
{
state: "CO",
miles: 5082
},
{
state: "TX",
miles: 582085
},
{
state: "IL",
miles: 9852
}
];
var tbody = $( "#my_table tbody" );
for( state_idx in stateMiles ) {
var state = stateMiles[ state_idx ];
tbody.append( $( "#row_template" ).html().replace( "{{state}}", state.state ).replace( "{{miles}}", state.miles ) );
}
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
<body>
<table id="my_table">
<thead>
<th>State</th>
<th>Miles</th>
</thead>
<tbody>
</tbody>
</table>
<script type="text/html" id="row_template">
<tr>
<td>{{state}}</td>
<td>{{miles}}</td>
</tr>
</script>
</body>
</html

Table content replaced with new one in JavaScript

If I click on the submit button, then insert new cell, and click more than one time cells inserts again and again in a table i want to only add items only one time in table not again and again.
i want to call clear previous data and add new one when call fillTable().
my code is below here
<html>
<body>
<input type="button" onclick="fillTable()" value="submit">
<div id="out" >
<h2>Results are</h2>
<table id="tblData" border="1">
<tr>
<th>Name</th>
<th>Share</th>
</tr>
</table>
</div>
<script>
function fillTable(){
clearCells(); // clear previous
var tableRef = document.getElementById("tblData");
var rowcount = tableRef.rows.length;
var newRow = tableRef.insertRow(rowcount);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
var newCell2 = newRow.insertCell(1);
var newText1 = document.createTextNode("Hello");
var newText2 = document.createTextNode("12000");
newCell.appendChild(newText1);
newCell2.appendChild(newText2);
newCell.appendChild(newText1);
newCell2.appendChild(newText2);
}
function clearCells(){
var tableRef = document.getElementById("tblData");
tableRef.deleteCell(0);
tableRef.deleteCell(1);
}
</script>
</body>
</html>
your problem was in your clearCell method, I fixed it for you:
function clearCells(){
var tableRef = document.getElementById("tblData");
if(tableRef.rows.length > 1){
tableRef.deleteRow(1);
}
}

Trouble with setting id for dynamically generated table

Never mind. This was my mistake. This code works fine.
I have a function that's supposed to create and populate a table. I'm also trying to set the id element of some of the columns, but the function that I have isn't working and I can't seem to figure out why.
This is my code:
HTML:
<div id="result_table">
<table border="0" cellspacing="3" cellpadding="3" id="summaryTable" class="tablesorter table table-striped">
<thead>
<tr style="font-weight: bold; text-align: center;">
<th>Well ID</th>
<th>Dominant Gene</th>
<th>%</th>
<th>Secondary Gene</th>
<th>%</th>
<th>No. of Reads that Mapped</th>
<th>No. of Mutations</th>
<th>Mutation Information</th>
<th>View</th>
</tr>
</thead>
<tbody id="summaryBody">
</tbody>
</table>
</div>
Javascript:
function structureTable(test){
if (kiloseqResult==null){
throw "Error: no databse defined"
};
document.getElementById("summaryTable").style.visibility="visible";
kiloseqDatabase = JSON.parse(kiloseqResult);
var table = document.getElementById("summaryBody");
for (i=0;i<kiloseqDatabase.length;i++){
var row = table.insertRow(i);
var kiloseqKeys = Object.keys(kiloseqDatabase[i])
var keyLength = Object.keys(kiloseqDatabase[i]).length;
// Painstakingly setting up the cells...
var cell = row.insertCell(0);
cell.innerHTML = kiloseqDatabase[i]['id']
var cell = row.insertCell(1);
cell.innerHTML = kiloseqDatabase[i]['gene1'].substr(5)
var cell = row.insertCell(2);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent1']).toFixed(2)
var cell = row.insertCell(3);
if (kiloseqDatabase[i]['gene2']=="None"){
cell.innerHTML = "None"
} else {
cell.innerHTML = kiloseqDatabase[i]['gene2'].substr(5)
}
var cell = row.insertCell(4);
cell.innerHTML = parseFloat(kiloseqDatabase[i]['percent2']).toFixed(2)
var cell = row.insertCell(5);
cell.innerHTML = kiloseqDatabase[i]['count']
var cell = row.insertCell(6);
cell.innerHTML = ""
var cell = row.insertCell(7);
cell.innerHTML = ""
var cell = row.insertCell(8);
cell.innerHTML = ""
};
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
};
kiloseqResult is a variable that checks whether kiloseqDatabase is populated. kiloseqDatabase contains the information that's supposed to populate the table.
Oddly enough, the for-loop that sets up the ID (and yes, I did try including this in the first for-loop but tried breaking it up when that didn't work) is fine when I run it in my Chrome's console. But it doesn't seem to work within the function.
Any help would be much appreciated. Thank you!
Have you tried putting your ID assignment logic within the document.ready scope? You can't assign an ID to an element or select it from the DOM before it's rendered:
$(document).ready(function()
{
$("#summaryTable").tablesorter(
{sortList: [[0,0], [1,0]]}
);
for (i=0;i<kiloseqDatabase.length;i++){
document.getElementById("summaryBody").rows[i].cells[6].id = "test";
};
}
);

Disregard a particular TD element

Below I have the code that allows me to edit a table row inline. However it edits ALL of the TDs within that row. My problem, along with the code, are stated below. Any help is appreciated.
<tbody>
<tr>
<th scope="row">Test</th>
<td class="amount">$124</td>
<td class="amount" id="" >$154</td>
<td class="diff">- 754</td>
</tr>
</tbody>
The above table is just a sample. What I have been trying to accomplish is, to simply edit the TDs within that particular row, but I need it to disregard the diff TD.
I'm fairly new to jQuery and have got the following code via the help of a jQuery book.
$(document).ready(function() {
TABLE.formwork('#current-expenses');
});
var TABLE = {};
TABLE.formwork = function(table){
var $tables = $(table);
$tables.each(function () {
var _table = $(this);
_table.find('thead tr').append($('<th class="edit"> </th>'));
_table.find('tbody tr').append($('<td class="edit"><input type="button" value="Edit"/></td>'))
});
$tables.find('.edit :button').live('click', function(e) {
TABLE.editable(this);
e.preventDefault();
});
}
TABLE.editable = function(button) {
var $button = $(button);
var $row = $button.parents('tbody tr');
var $cells = $row.children('td').not('.edit');
if($row.data('flag')) { // in edit mode, move back to table
// cell methods
$cells.each(function () {
var _cell = $(this);
_cell.html(_cell.find('input').val());
})
$row.data('flag',false);
$button.val('Edit');
}
else { // in table mode, move to edit mode
// cell methods
$cells.each(function() {
var _cell = $(this);
_cell.data('text', _cell.html()).html('');
if($('td.diff')){
var $input = $('<input type="text" />')
.val(_cell.data('text'))
.width(_cell.width() - 16);
_cell.append($input);
}
})
$row.data('flag', true);
$button.val('Save');
}
}
I have attempted to alter the code so that it would disregard the diff class TD, but have had no luck so far.
Replace
var $cells = $row.children('td').not('.edit');
with
var $cells = $row.children('td').not('.edit').not('.diff');
Add one more line after:
var $cells = $row.children('td').not('.edit').not('.diff');

Categories