How would I transform a table
<table>
<tr>
<td>Name</td>
<td>Price</td>
</tr>
<tr>
<td>Name</td>
<td>Price</td>
</tr>
</table>
to a list of paragraphs with jQuery
<ul>
<li>
<p>Name</p>
<p>Price</p>
</li>
<li>
<p>Name</p>
<p>Price</p>
</li>
</ul>
<p><a id="products-show-list">Toggle list view</a></p>
<script type="text/javascript">
$("#products-show-list").click(function(){...});
</script>
function convertToList(element) {
var list = $("<ul/>");
$(element).find("tr").each(function() {
var p = $(this).children().map(function() {
return "<p>" + $(this).html() + "</p>";
});
list.append("<li>" + $.makeArray(p).join("") + "</li>");
});
$(element).replaceWith(list);
}
You could try:
function convertToList() {
var list = $("<ul></ul>");
$("table tr").each(function() {
var children = $(this).children();
list.append("<li><p>" + children[0].text() + "</p><p>" + children[1] + "</p></li>");
}
$("table").replaceWith(list);
}
This still has some work left, but this is what I got to work so far:
<script>
$(function(){
t2l("uglytable");
});
function t2l(divname)
{
var ulist = $("<ul></ul>");
var table = "div." + divname + " table";
var tr = "div." + divname + " table tr";
$(tr).each(function(){
var child = $(this).children();
ulist.append("<li>" + child.text() + "</li>");
});
$(table).replaceWith(ulist);
}
</script>
<div class="uglytable">
<table border="1">
<tr>
<td>lakers</td>
</tr>
<tr>
<td>dodgers</td>
</tr>
<tr>
<td>angels</td>
</tr>
<tr>
<td>chargers</td>
</tr>
</table>
</div>
I can see this being useful in SharePoint which likes to use a bunch of nested tables to render a simple list which is more efficient using , ...
Related
I am trying to build a table that will allow users to change the value of a cell(s) and then "submit" that data
to a JavaScript (only please) method that turns the tables data into a json dataset.
I started by trying to updated the value of just one field. QTY in this case. I am able to loop over the table and get the static values, but I am not able to catch the user input value.
question: What is a JavaScript only (if possible) way to capture user change(able) values from a table?
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).innerHTML;
//alert("qty: " + wty);
qty = qty.substr(oCells.item(2).innerHTML.indexOf('value=') + 7);
qty = qty.substr(0, qty.indexOf('" class='));
//alert(qty);
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
THANK YOU
Instead of selecting the entire td element, retrieve only what you really need using querySelector (or use jQuery if possible). Find the input element and access the value, it's a lot easier than doing all of that unecessary parsing of the inner html of the entire cell.
function updateQTY() {
//getData from table
//gets table
var lines = "";
var oTable = document.getElementById('items');
//gets rows of table
var rowLength = oTable.rows.length;
var line = "";
//loops through rows, skips firts row/header
for (i = 1; i < rowLength; i++) {
//gets cells of current row
var oCells = oTable.rows.item(i).cells;
var qty = oCells.item(2).querySelector(".mdl-textfield__input").value;
line = line +
'{ "item": "' + oCells.item(0).innerHTML + '",' +
' "discription": "' + oCells.item(1).innerHTML + '",' +
' "qty": "' + qty + '"},'
}
//alert(line);
var jsonData = JSON.parse('[' + line + '{"quickwayto":"dealwith,leftbyloop"}]');
alert("lines: " + JSON.stringify(jsonData));
}
<form action='#'>
<table class='mdl-data-table mdl-js-data-table' id='items'>
<thead>
<tr>
<th>item</th>
<th>discription</th>
<th>QTY</th>
</tr>
</thead>
<tbody>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_1 </td>
<td class='mdl-data-table__cell--non-numeric'>it's fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty1' id='value1' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
<tr>
<td class='mdl-data-table__cell--non-numeric'> widget_2 </td>
<td class='mdl-data-table__cell--non-numeric'>it's super fun</td>
<td>
<div class='mdl-textfield mdl-js-textfield'><input type='text' name='qty2' id='value2' value='5' class='mdl-textfield__input'></div>
</td>
</tr>
</tbody>
</table>
<div>
<input type='button' value='update' onclick='updateQTY()' class='mdl-button mdl-js-button mdl-button--raised mdl-js-ripple-effect'>
</div>
</form>
You need to use document.getElementById('value2').value instead of .innerHTML.indexOf('value=')
You're making yourself a lot of work here. You have a table. All you need to do is convert that to JSON. I would suggest you look at the library below that does that in around one line of native java-script.
http://www.developerdan.com/table-to-json/
In my table I have 2 rows please see my screen shot,suppose I click first check box means I want to take that id ** and **to_area value in jquery how can do this,I tried but I can not get please help some one
$(document).ready(function() {
$('#chemist_allotment_btn').click(function() {
if ($('#chemist_allotment_form').valid()) {
$.ajax({
url: 'update_chemist_bulk_transfer.php',
type: 'POST',
data: $('form#chemist_allotment_form').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data); // convert the json
console.log(res);
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function(key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td>' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td>' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
$('#SampleDT tbody').empty().append(htmlString);
$('#get_to_area').click(function() {
var id = $('input[name=getchemist]:checked').val();
if ($(".getchemist").prop('checked') == true) {
alert(id);
alert(value.to_area);
} else {
alert('Please Check');
}
});
} else {
$('#SampleDT tbody').empty().append('No Datas Found');
}
},
});
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<center>
<div class="form-group">
<button type="button" class="btn btn-primary" style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
Firstly, add classes to each <td>, like <td class='id'>[Your id]</td>
Similarly for all the elements doctor-name, to-area, etc and a class to each <tr> like row-select
Somewhat like this:
<tr class="row-select">
<td class="select">...</td>
<td class="id">...</td>
<td class="to-area">...</td>
.
.
.
</tr>
Use jQuery like this:
$('.row-select').click(function(){
var id,toArea,checkBox;
id = $(this).find('.id').html(); //get the ID field
toArea = $(this).find('.to-area').html(); //get the to-area field
checkBox = $(this).find('.select > input');
checkbox.prop('checked',!checkbox.prop('checked'));
})
This code will get you he value no mater where you click on the row, and also invert the selection on the checkbox
To get the values of rows selected when the form is submitted run a loop like this
$('.row-select input:checked').each(function(){
var id,toArea,checkBox;
id = $(this).closest('tr').find('.id').html(); //get the ID field
toArea = $(this).closest('tr').find('.to-area').html(); //get the to-area field
})
EDIT
All together:
$(document).ready(function() {
$('#btnSubmit').click(function() {
$('.row-select input:checked').each(function() {
var id, name;
id = $(this).closest('tr').find('.id').html();
name = $(this).closest('tr').find('.name').html();
alert('ID: ' + id + " | Name: " + name);
})
})
$('#btnSelectAll').click(function() {
$('.row-select input').each(function() {
$(this).prop('checked', true);
})
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">12</td>
<td class="name">Jones</td>
</tr>
<tr class="row-select">
<td class="check">
<input type="checkbox" />
</td>
<td class="id">10</td>
<td class="name">Joseph</td>
</tr>
</table>
<button id="btnSelectAll">Select all</button>
<button id="btnSubmit">Get Value</button>
Process step-by-step:
Give the td you need some classes (from-a & to-a);
Initialize an empty array all (we'll store the data inside it later on);
Create a function that is triggered by the checkbox change
Inside the function you need to know which checkbox has changed, what's the state of it, what tr does it belong to and at the end what are the TO AREA and FROM AREA values.
If the state = checked we will add the values to the all (our small data storage);
If the state = not-checked we will remove the value from the all array;
Finally when we are done with selecting and deselecting rows by pressing the button we can get the values of the selected rows.
var all = [];
$('input[type="checkbox"]').change(function(){
var checkbox = $(this);
var state = checkbox.prop('checked');
var tr = checkbox.parents('tr');
var from = tr.children('.from-a').text();
var to = tr.children('.to-a').text();
if(state){
all.push(from + ' -> ' + to);
}else{
var index = all.indexOf(from + ' -> ' + to);
all.splice(index, 1);
}
})
$('#get_to_area').click(function(){
alert(all);
});
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class="well white">
<table id="SampleDT" class="datatable table table-hover table-striped table-bordered tc-table">
<thead>
<tr>
<th>Select</th>
<th>Id</th>
<th>Doctor Name</th>
<th>From Area</th>
<th>To Area</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<tr id="1">
<td><input type="checkbox"></td>
<td>1</td>
<td>Nick</td>
<td class="from-a">Kosur</td>
<td class="to-a">Nath Pari</td>
<td>Address</td>
</tr>
<tr id="2">
<td><input type="checkbox"></td>
<td>2</td>
<td>John</td>
<td class="from-a">Rusok</td>
<td class="to-a">iraP htaN</td>
<td>sserddA</td>
</tr>
</tbody>
</table>
<center>
<div class="form-group">
<button style="text-align:left;" id="get_to_area">Transfer Area</button>
</div>
</center>
</div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
</body>
</html>
This is just the basic concept, you can modify it to suit your needs, I'll be happy to help you if you get stuck.
You can also use this fiddle:
In JS:
$('#get_to_area').click(function () {
var id = $('input[name=getchemist]:checked').val();
if ($('input[name=getchemist]').is(':checked')) {
var ID = $('input[name=getchemist]').parent().parent().siblings('td.chkid').html();
var TO_Area = $('input[name=getchemist]').parent().parent().siblings('td.toarea').html();
}
else {
alert('Please Check');
}
});
In Html:
if (res['status'] == 1) {
var htmlString = '';
$.each(res['data'], function (key, value) {
htmlString += '<tr>';
htmlString += ' <td class="sorting_1"><div class="checkbox-custom checkbox-success"><input type="checkbox" id="checkboxExample3" name="getchemist" class="getchemist" value="' + value.id + '"><label for="checkboxExample3"></label></div></td>';
htmlString += '<td class="chkid">' + value.id + '</td>';
htmlString += '<td>' + value.name + '</td>';
htmlString += '<td>' + value.area + '</td>';
htmlString += '<td class="toarea">' + value.to_area + '</td>';
htmlString += '<td>' + value.address + '</td>';
htmlString += '</tr>';
});
I'm guessing you need values of each td whose checbox are checked. This piece of code should get you started.
As you can see, Code loops through each checkbox which is checked, gets contents inside its corresponding td.
var Result = new Array();
$('.checkbox-custom input[type="checkbox"]:checked').each(function(){
var _this = $(this).closest('tr').find('td');
var id= $(_this).eq(0);
var name = $(_this).eq(1);
................... //Similar way for the others
Result.Push(id,name,....)
});
I have the following table
<table class="hTab">
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
<tr class="hTr"> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
I have used following jQuery code to show the rows one by one (I have declared 10 rows in the table)
var currentrow = 0;
$('#hTab #hTr').hide();
$('#hTab #tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('#hTab #hTr:eq(' + currentrow + ')').show();
});
But at the moment it's not working. If anyone can show me the error in my code, it will be very helpful
You should use class selector . instead of id selector #, e.g :
$('.hTab .hTr:eq(' + currentrow + ')').show();
So the code will be :
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
NOTE : the button shouldn't be inside tr tag because it's outside of the table, and you have to add tds inside every tr.
Hope this helps.
var currentrow=0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"><td> A </td></tr>
<tr class="hTr"><td> B </td></tr>
<tr class="hTr"><td> C </td></tr>
</table>
<input type=button value="Show 1 more" id="onemore" />
hTab and hTr is class not a id:
so use everywhere:
$('.hTab .hTr')
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab .hTr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table class="hTab">
<tr class="hTr"> <td>A<td> </tr>
<tr class="hTr"> <td>B<td> </tr>
<tr class="hTr"> <td>C<td> </tr>
</table>
<tr> <input type=button value="Show 1 more" id="onemore" /></tr>
please see the fiddle link
var currentrow = 0;
$('.hTab .hTr').hide();
$('.hTab tr:eq(0)').show();
$("#onemore").click(function () {
currentrow++;
$('.hTab .hTr:eq(' + currentrow + ')').show();
});
I'm creating a userscript that collects and displays text from the following table using javascript / jQuery:
<table id="table-cours">
<tbody>
<tr>
<td class="calendar-time"> time1 </td>
<td>
<div class = popup-calendar-event> popup content 1 </div>
<div class = "link-event"> event 1 </div>
</td>
</tr>
<tr>
<td class="calendar-time"> time2 </td>
<td>
<div class = popup-calendar-event> popup content 2 </div>
<div class = "link-event"> event 2 </div>
</td>
</tr>
<tr>
<td class="calendar-time"> time3 </td>
<td>
<div class = popup-calendar-event> popup content 3 </div>
<div class = "link-event"> event 3 </div>
</td>
</tr>
</tbody>
</table>
I want to collect all the text contained in this table except that which is contained within the div.popup-calendar-event elements.
My objective is to display it like this:
time 1 : event 1
time 2 : event 2
time 3 : event 3
The problem is that the number of lines of the table can change, here I put 3 lines but they can be 1 or 10 or any other number.
I tried many ways like using the not() method, or a for() loop with an array of "tr" elements but it never works.
$('tr').each(function(data) {
var calTime = $(this).find('.calendar-time')[0].innerHTML;
var linkEvent = $(this).find('.link-event')[0].innerHTML;
$("#result").append('<li><b>' + calTime + '</b> : ' + linkEvent + '</li>');
console.log('<li><b>' + calTime + '</b> : ' + linkEvent + '</li>');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id="table-cours">
<tbody>
<tr>
<td class="calendar-time">time1</td>
<td>
<div class=p opup-calendar-event>popup content 1</div>
<div class="link-event">event 1</div>
</td>
</tr>
<tr>
<td class="calendar-time">time2</td>
<td>
<div class=p opup-calendar-event>popup content 2</div>
<div class="link-event">event 2</div>
</td>
</tr>
<tr>
<td class="calendar-time">time3</td>
<td>
<div class=p opup-calendar-event>popup content 3</div>
<div class="link-event">event 3</div>
</td>
</tr>
</tbody>
</table>
<ul id="result"></ul>
You can use something like this to parse table content and obtain an array of objects
var data = $('#table-cours > body > tr').map(function($i, $r) {
var $row = $(this);
return {
title: $row.find('.calendar-time').text(),
event: $row.find('.link-event').text()
};
}).get();
After that you can use data array for whatever you need.
You can try something like
$(".calendar-time").each(function () {
console.log($(this).html() + '-' + $(this).next('td').find('.link-event').html());
});
fiddle demo-http://jsfiddle.net/bL644p7b/
$(function(){
$("#table-cours .popup-calendar-event").each(function(iter, item){
$(".result").append("<div> time "+(iter+1) +" "+ $(this).text() +"</div>");
});
});
You just each a each method to iterate. The first argument is the iterator.
http://jsfiddle.net/qufgyh3c/
var rows = $('#table-cours > tr');
var map = {};
rows.each(function(row){
var key = $(row).find('td.calendar-time');
var value = $(row).find('td > div.link-event');
map[key]=value;
});
$(document).ready(function() {
$(".calendar-time").each(function() {
var output = "";
output += $(this).text() + " : ";
output += $(this).next().find(".link-event").text();
$(".output").append(output);
});
});
JSFiddle: https://jsfiddle.net/cq772j9s/
I would do:
$.each($('#table-cours tr'), function (i, val) {
$('#results ul').append('<li><strong>' + $(val).find('td.calendar-time').text() + '</strong>:' + $(val).find('.link-event').text() + '</li>');
});
example fiddle here
I have a DOM with different nested divs and inputs (with values):
<div id ="div_id1">
<div id ="div_id2">
<table>
<tr>
<td>input 1:</td>
<td><input id="i1" type="text"/></td>
</tr>
<tr>
<td>input 2:</td>
<td><input id="i2" type="text"/></td>
</tr>
<tr>
<td>input 3:</td>
<td><input id="i3" type="text"/></td>
</tr>
</table>
<div id ="div_id3">
<table>
<tr>
<td>input 4:</td>
<td><input id="i4" type="text"/></td>
</tr>
<tr>
<td>input 5:</td>
<td><input id="i5" type="text"/></td>
</tr>
</table>
</div>
</div>
How to make XML string recursively according to this structure?
Like this:
<div_id1>
<div_id2>
<i1>value 1</i1>
<i2>value 2</i2>
<i3>value 3</i3>
<div_id3>
<i4>value 4</i4>
<i5>value 5</i5>
</div_id3>
</div_id2>
UPD:
I tried function like this:
function makeXml(nodes) {
var $result = $('<' + nodes.attr('id') + '>');
$.each(nodes, function(i, node) {
var nodeId = node.getAttribute('id');
var $el = $('<' + nodeId + '>').text($('#' + nodeId).val());
alert(nodeId + $('#' + nodeId).val());
$el.appendTo($result);
var $children = $(node).children();
if ($children.length > 0) {
makeXml($children).appendTo($el);
}
});
return $result;
};
But it does not work properly (does not correctly handle nested divs).
Does anyone have any solution?
One of the options (create a XML-string):
var str = '';
function makeXml(obj) {
var children = obj.children();
if (children.size() != 0) {
$.each(children, function(i, v) {
var $val = $(v), id = $val.attr('id');
if (typeof($val.attr('id')) !== "undefined") {
str += '<' + id + '>' + $('#' + id).val();
makeXml($val);
str += '</' + id + '>';
} else {
makeXml($val);
}
});
}
}