How can I get element's data to Array with jQuery? - javascript

Here is a table:
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
I want to get every tr's data-id,
I know how to get it with $.each,
I know this can do it:
var trArray = [];
$.each($('table tr'), function () {
trArray.push($(this).data('id'));
})
and $('table tr').data('id') only can get the first tr's data-id
But is there anyway easy and graceful to do this?
In one sentence to get data-id's array [1,2,3,4,5,6] with jQuery or js?

Try using $.map()
var data = $.map($("table tr"), function(el) {return $(el).data().id})

This is another option, which uses pure js.
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var toarray = function(e){ return [].slice.call(e) }
var ids = toarray(document.querySelectorAll("tr")).map(function(e){
return e.dataset.id;
});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
You could 'simplifly' like this if you want
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
var getIds = function() {
var ids = [].slice.call(document.querySelectorAll("tr")).map(function(e){return e.dataset.id});
alert(ids)
};
document.addEventListener("DOMContentLoaded", getIds);
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>
Here's the jQuery option:
var ids = $.map($("tr"),function(e){return e.dataset.id});
var getIds = function() {
var ids = $.map($("tr"),function(e){return e.dataset.id});
alert(ids);
};
document.addEventListener("DOMContentLoaded", getIds);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-id="1">xxx</tr>
<tr data-id="2">xxx</tr>
<tr data-id="3">xxx</tr>
<tr data-id="4">xxx</tr>
<tr data-id="5">xxx</tr>
<tr data-id="6">xxx</tr>
</table>

Related

KnockoutJS - show accumulate value for each item

How can I display in a table the accumulate value for each item in a observableArray with KnockoutJS?
I need somethin like:
function ViewModel(){
var self = this;
self.Item = function(day,note){
this.day = ko.observable(day);
this.note = ko.observable(note);
};
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
var vm = new ViewModel();
var arrItems = ko.utils.arrayMap(itemsFromServer, function(item) {
return new vm.Item(item.day, item.note);
});
ko.applyBindings(vm);
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr><th>Day</th><th>Note</th><th>Accumulate</th></tr>
</thead>
<tbody data-bind="foreach: arrItems">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td >the currente 'note' + the anterior 'note'</td>
</tr>
</tbody>
</table>
The last column should display the sum of current item + anterior item.
Thanks.
I'm not exactly sure what value you want the third column to be, but the main approach remains the same:
Give your Item class access to their "sibling items" by passing a reference to the array
In a computed property, do a "look behind" by looking up the items own index.
Perform some sort of calculation between two (or more) Item instances and return the value
For example, this acc property returns the acc of the previous Item and ones own note property:
var Item = function(day, note, siblings){
this.day = ko.observable(day);
this.note = ko.observable(note);
this.acc = ko.pureComputed(function() {
var allItems = siblings();
var myIndex = allItems.indexOf(this);
var base = myIndex > 0
? allItems[myIndex - 1].acc()
: 0
return base + this.note();
}, this);
};
function ViewModel() {
var self = this;
self.items = ko.observableArray([]);
self.items(itemsFromServer.map(function(item) {
return new Item(item.day, item.note, self.items);
})
);
}
var itemsFromServer = [
{day:'Mo', note:1},
{day:'Tu', note:2},
{day:'We', note:3},
{day:'Th', note:4},
{day:'Fr', note:5},
{day:'Su', note:6},
];
ko.applyBindings(new ViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.4.2/knockout-min.js"></script>
<table>
<thead>
<tr>
<th>Day</th>
<th>Note</th>
<th>Accumulate</th>
</tr>
</thead>
<tbody data-bind="foreach: items">
<tr>
<td data-bind="text: day"></td>
<td data-bind="text: note"></td>
<td data-bind="text: acc"></td>
</tr>
</tbody>
</table>

Jquery, how to select an element by its first position value of an attribute

In html:
<tr data-s=""></tr>
<tr data-s="1"></tr>
<tr data-s="2 1"></tr>
<tr data-s="3 2 1"></tr>
I'm trying to build a selector in order to get the trs by the value of the first position of data-s attribute.
Thanks in advance.
You can get the element by first position of data-s attribute as far as I understood.
$('[data-s^="3 "]');
Or if you want to get first position of data-s attribute's value, you can do this;
$('[data-s]').data('s').split(' ')[0];
There is a plunker example for you.
You can use .split(" ")[0] to get first value of data-s attribute
$("table tr").each(function() {
console.log($(this).attr("data-s").split(" ")[0])
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<table>
<tr data-s=""></tr>
<tr data-s="1"></tr>
<tr data-s="2 1"></tr>
<tr data-s="3 2 1"></tr>
</table>
My proposal is based on jQuery.filter function:
$(function () {
var elements = $('table tr').filter(function(index, element) {
return this.getAttribute('data-s').split(' ')[0] == '1';
});
console.log(elements.length);
});
<script src="https://code.jquery.com/jquery-1.12.1.min.js"></script>
<table>
<tr data-s=""></tr>
<tr data-s="1"></tr>
<tr data-s="2 1"></tr>
<tr data-s="3 2 1"></tr>
</table>
function customFn(elm,sel)
{
var tmp = $();
$(elm).each(function(){
data=$(this).data('s').toString().split(' ')[0];
if(data.trim()===sel.toString().trim())
tmp=tmp.add(this);
});
return tmp
}
customFn("tr","3");
https://jsfiddle.net/68x8Leuz/
$('[data-s]').each(function () {
var test = $(this).attr('data-s')
if(test != undefined){
var firstDataValue = parseInt(test.split(' ')[0]);
/*run you test case for first value and return back this on success */
}
})

How to get value from list table tr

HTML :
<table id="gwAssignForm">
<tr data-id="1"></tr>
<tr data-id="2"></tr>
<tr data-id="3"></tr>
<tr data-id="4"></tr>
<tr data-id="5"></tr>
</table>
And javascript :
var product_id = [];
$("#gwAssignForm tr[data-id]").each(function () {
product_id.push($(this).text());
});
var result = '"' + product_id.join('", "') + '"';
How to get list id, with result: 1, 2, 3, 4, 5
text() will give you the innerText of the element. Use data().
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute.
Use data('id') to get the data-id attribute value.
var product_id = [];
$("#gwAssignForm tr[data-id]").each(function() {
product_id.push($(this).data('id'));
});
document.write(product_id);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<table id="gwAssignForm">
<tr data-id="1"></tr>
<tr data-id="2"></tr>
<tr data-id="3"></tr>
<tr data-id="4"></tr>
<tr data-id="5"></tr>
</table>

How to collect all data attributes and push to an array

I have a series of table rows with data attributes. I would like to collect all the value of these data attributes and add them to an array. How do I do this?
<tr data-title-id="3706" role="row" class="odd"></tr>
<tr data-title-id="3707" role="row" class="odd"></tr>
Or the simplest method which will create the array and fill it in one step:
var dataIds = $("table tbody tr").map(function() { return $(this).data('title-id'); });
You could do something like this:
var data = [];
$('tr', yourTable).each(function() {
data.push($(this).attr('data-title-id'));
}
It can be useful to get all data attrs to array of objects.
var a = $('tr').map(function(x){
return $(this).data();
}).toArray();
alert(JSON.stringify(a,null,'\t'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body><table>
<tr data-title-id="3706" data-title-val="Hello" role="row" class="odd"></tr>
<tr data-title-id="3707" role="row" class="odd"></tr>
</table></body>

create json object from html table using selected colums using jquery

i was wondering how to parse html table to get json object that i can send via $.post with jquery.
i have a table
<table id="Report">
<thead>
<tr>
<th>Kod</th>
<th>Nazwa</th>
<th>Ilość</th>
<th>Netto / 1szt.</th>
<th>Suma brutto</th>
</tr>
</thead>
<tbody>
<tr>
<td>00171 </td>
<td>SŁUP 50/1800 POŚREDNI(P) </td>
<td>5</td><td>97.00 PLN </td>
<td>394.31 PLN </td>
</tr>
<tr>
<td>00172</td>
<td>SŁUP 50/1800 NAROŻNY(P)</td>
<td>1</td><td>97.00 PLN</td>
<td>78.86 PLN</td>
</tr>
<tr>
<td>00173 </td>
<td>SŁUP 50/1800 KOŃCOWY(P) </td>
<td>1</td><td>97.00 PLN </td>
<td>78.86 PLN</td>
</tr>
</tbody>
<tfoot style="font-weight: bold;">
<tr>
<th colspan="3" style="text-align: right;">Razem netto: 1955.85 PLN</th>
<th colspan="2" style="text-align: right;">Razem brutto: 2405.69 PLN</th>
</tr>
</tfoot>
</table>
and what i need is json object in this format (first <td> and third <td>):
[{"00171":5},
{"00172":1},
{"00173":1}
]
and that i can send it via
$.post(
"print.php",
{json: myjsonvar},
"json"
);
any idea how to do that?
thanks
var json = [];
$('#Report').find('tbody tr').each(function(){
var obj = {},
$td = $(this).find('td'),
key = $td.eq(0).text(),
val = parseInt( $td.eq(2).text(), 10 );
obj[key] = val;
json.push(obj);
});
How about:
var myjsonvar=[];
$('#Report tbody tr').each(function(){
var data={};
var tr=$(this);
data[tr.find('td:first-child').text()]=tr.find('td:nth-child(3)').text();
myjsonvar.push(data);
});
var sendData = [];
$('#Report tbody tr').each(function(i, el){
var key = $.trim($(this).find('td:eq(0)').text()),
val = $.trim($(this).find('td:eq(2)').text()),
obj = {};
obj[key] = val;
sendData.push(obj);
});
See demo
Why json, if you are in js already? Just create a simple object:
var data = {};
$("#Report tbody tr").each(function() {
data[$(this).children("td:eq(0)").text()] = $(this).children("td:eq(2)").text();
});
$.post("print.php", data);
Setting type to json in $.post defines the server response to be json, not the send data!
http://jsfiddle.net/zyCPN/
var objArray=[];
$('table#Report tbody tr').each(function(i){
var row=$(this);
obj={};
obj[$('td', row).eq(0).text()]=$('td', row).eq(2).text();
objArray.push(obj);
});

Categories