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>
Related
I am wanting to concatenate strings from 2 separate elements and have them stored in a variable.
Currently my code is setting the variable equal to:
"Daily: 1070300, Weekly: 1070300, Monthly: 1070300"
My goal is to make the variable in the console equal to:
"Daily: 10, Weekly: 70, Monthly: 300"
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function() {
str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
Thank you for your help all!
Each time through the key loop, you're grabbing the content of all three value cells (since $(this).parents().siblings('tr').find('.value') matches all three). There are many ways to fix this but one easy one I see is to use the index argument on the inner loop to select the value cell corresponding to the current key (using jQuery's eq function):
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function(index) {
str += $(this).text() + ": " + $(this).parents().siblings('tr').find('.value').eq(index).text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
The code is very inefficient when you keep looking up stuff in the loop. So fixing it to read the index would work, it just causes the code to do more work than needed.
How can it be improved. Look up the two rows and one loop using the indexes.
var keys = $("table .key") //select the keys
var values = $("table .value") //select the values
var items = [] // place to store the pairs
keys.each(function(index, elem){ //loop over the keys
items.push(elem.textContent + " : " + values[index].textContent) // read the text and use the index to get the value
})
console.log(items.join(", ")) // build your final string by joing the array together
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
</table>
Collect the .key and .value classes into a NodeList convert the NodeList into arrays. Then merge the 2 arrays into key/value pairs stored in an Object Literal. Finally convert the object into a string so it can be displayed.
Demo
Details are commented in Demo
// Collect all th.key into a NodeList and turn it into an array
var keys = Array.from(document.querySelectorAll('.key'));
// As above with all td.value
var vals = Array.from(document.querySelectorAll('.value'));
function kvMerge(arr1, arr2) {
// Declare empty arrays and an object literal
var K = [];
var V = [];
var entries = {};
/* map the first array...
|| Extract text out of the arrays
|| Push text into a new array
|| Then assign each of the key/value pairs to the object
*/
arr1.map(function(n1, idx) {
var txt1 = n1.textContent;
var txt2 = arr2[idx].textContent;
K.push(txt1);
V.push(txt2);
entries[K[idx]] = V[idx];
});
return entries;
}
var result = kvMerge(keys, vals);
console.log(result);
// Reference the display area
var view = document.querySelector('.display');
// Change entries object into a string
var text = JSON.stringify(result);
// Clean up the text
var final = text.replace(/[{"}]{1,}/g, ``);
// Display the text
view.textContent = final
<table>
<tbody>
<tr>
<th class="key">Daily</th>
<th class="key">Weekly</th>
<th class="key">Monthly</th>
</tr>
<tr>
<td class="value">10</td>
<td class="value">70</td>
<td class="value">300</td>
</tr>
</tbody>
<tfoot>
<tr>
<td class='display' colspan='3'></td>
</tr>
</tfoot>
</table>
You can also solve that using unique ids, like that:
$(document).ready(function() {
var str = '';
$('tbody > tr').each(function() {
$(this).find('.key').each(function() {
var index = $(this).attr('id').slice(3)
str += $(this).text() + ": " + $('#value'+index).text() + ", ";
})
});
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody>
<tr>
<th class="key" id="key1">Daily</th>
<th class="key" id="key2">Weekly</th>
<th class="key" id="key3">Monthly</th>
</tr>
<tr>
<td class="value" id="value1">10</td>
<td class="value" id="value2">70</td>
<td class="value" id="value3">300</td>
</tr>
</tbody>
</table>
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 */
}
})
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>
I need to highlight some rows of my table. This highlight is based on the rows present in my response object. This object can be as follow:
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
</tbody>
</table>
Here is my javascript code:
var id = $("tbody tr", response).attr('id');
var cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
This works fine only if my response object contains only 1 row. Now I need to be able to highlight more than 1 rows at a time. So for example with the response object below:
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
<tr id="13954">
<td>MIKE GIVER</td>
<td>ARGO INTERNATIONAL CORP</td>
</tr>
</tbody>
</table>
Any idea how to adapt my javascript code for that purpose ?
If you really want to do it the way you are doing it, than you need to use each
var trs = $("tbody tr", response);
trs.each( function () {
var id = this.id,
cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
});
Better off returning a JSON object with ids to select.
attr returns a single value, regardless how many elements are matched by the proceeding selector.
If you want to map every selected element to an ID and return array, you need map:
var ids = $("tbody tr", response).map(function (i, e) { return $(e).attr('id'); });
Once you have your list of IDs, you can iterate over that list, and highlight the matching rows in the DOM:
ids.forEach(function (id) {
var cols = $('#' + id + ' td');
cols.effect("highlight", {}, 30000);
});
Here is a working snippet.
The idea is to scrap the ids from the response you get by looping the tr nodes, from these ids build a css selector for the nodes you are interested in, and finally highlight all them.
function highlight(response){
// retrieve the ids from the response
var ids = $(response).find("tbody tr").map(function(){
// `this` will be the trs one after the other.
// `map` will put all returned values in an array.
return this.getAttribute("id");
}).get();
// build the css selector
var selector = "#" + ids.join(",#");
// highlight the corresponding nodes
$(selector).effect("highlight", {}, 30000);
}
// Call highlight with your response example.
highlight('<table id="ListRequests" class="table table-striped"><tbody><tr id="13955"><td>JEAN DUPONT</td><td>ACLIMEX SPRL</td></tr><tr id="13954"><td>MIKE GIVER</td><td>ARGO INTERNATIONAL CORP</td></tr></tbody></table>');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script>
<table id="ListRequests" class="table table-striped">
<tbody>
<tr id="13955">
<td>JEAN DUPONT</td>
<td>ACLIMEX SPRL</td>
</tr>
<tr id="13954">
<td>MIKE GIVER</td>
<td>ARGO INTERNATIONAL CORP</td>
</tr>
<tr id="1211">
<td>OTHER ONE</td>
<td>MUSN'T BE HIGHLIGHTED</td>
</tr>
</tbody>
</table>
I am having a table
<table width="100%" border="0" cellpadding="2" cellspacing="0" class="msctrans_navtree">
<tr class="msctrans_navrow" data-subs="603" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents</td>
</tr>
<tr class="msctrans_navrow" data-subs="" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test 1</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents 1</td>
</tr>
<tr class="msctrans_navrow" data-subs="334,23,5,21" data-navlevel="1" data-sp_id="2" data-standardsprache="1">
<td><strong>Test 2</strong></td>
</tr>
<tr>
<td bgcolor="#ffffff" colspan="2">List of documents 2</td>
</tr>
Clicking on the TR with class "msctrans_navrow" should do something regarding the data parameters of the clicked element:
$(".msctrans_navrow").click(function() {
var clicked = $(this);
var subs = clicked.data("subs");
var navlevel = clicked.data("navlevel");
var sp_id = clicked.data("sp_id");
var spstandard = clicked.data("standardsprache");
alert(subs + " = " + subs.length);
// Action only if there are subs
if (subs.length) {
clicked.toggleClass("mscajaxloaderdivabsolut");
var insertAfter = clicked.next();
alert("Now I am doing some Ajax and inert it after the inserAfter element.");
}
});
Unfortunately when clicking the first TR where the data-subs parameters value is 603 subs.length in the script delivers an "undefined". I can't figure why that is.
Here is a fiddle to play around with it: http://jsfiddle.net/9B9AW/9/
It's because it's stored as a number, not a string, inside jQuery's data cache for that element. Numbers don't have a length property. You could force a conversion to string by calling .toString():
if(subs.toString().length) {
// code if the string representation of `subs` has a length > 0
}
Alternatively you could use the .attr() method instead, which won't convert (always retrieves the value as a string):
var subs = clicked.attr("data-subs");
Change var subs = clicked.data("subs");
to var subs = ""+clicked.data("subs"); // make it a String
Demo ---> http://jsfiddle.net/9B9AW/10/