jquery efficient way to select tablerow data - javascript

I have a table with multiple rows of the same pattern:
<tr role="row" class="even">
<td><input type="checkbox" id="valj4"></td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko</td>
<td>Grundinställningar</td>
</tr>
Each row has a checkbox with unique ID, what would be the most efficient way to get a list of UUIDs for the rows with a checked checkbox. I would like to use jQuery.

$(function() {
var texts = [];
$('tr td:has(input:checkbox:checked) ~ td > a').each(function(i, e) {
texts.push($(e).attr('href'));
});
$('#result').html(texts.join('<br/>'));
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...5)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4">
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...6)
</td>
<td>Grundinställningar</td>
</tr>
<tr role="row" class="even">
<td>
<input type="checkbox" id="valj4" checked>
</td>
<td>Generell grupp</td>
<td>IKT Ipad11- Mirko (...7)
</td>
<td>Grundinställningar</td>
</tr>
</table>
<div id="result"/>
Getting the UUID is then an easy exercise in string chopping.

I assume your table has an id and it's "#table-id":
$("#table-id").find(":checked")
would get you all the checked checkboxes and radio boxes.
$("#table-id").find("input[type='checkbox']:checked")
would get you all the checked checkboxes.
var ids = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
ids += $(this).attr("id") + ",";
});
would give you a comma seperated list containing the ids of checked checkboxes in the table.
and the UUIDS list:
var UUIDs = "";
$("#table-id").find("input[type='checkbox']:checked").each(function(){
var href = $(this).closest("tr").find("td > a").first().attr("href");
var UUID = href.split('?')[1];
UUIDS += UUID + ",";
});

I would try the following
var ids = [];
$("#table input:checkbox:checked").each(function () {
var uuid = getParameter($(this).closest('tr').find('a').eq(0).attr('href'))
ids.push(uuid);
});
function getParameter(url) {
var regex = new RegExp("[\\?&]uuid=([^&#]*)"),
results = regex.exec(url);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
where #table is the id of your table
Example

jQuery('#formId').find('tr[class=even]').each(function () {
var rowId = "";
this.find('input[type=checkbox]').each(function() {
if(this.checked) {
rowId = "row" + $(this).val();
}
});
$(this).attr('id', rowId);
});

Create a new list of UUIDs.
var listOfUUIDs = [];
Get the checked input, go up to grandparent (the tr), then find the a inside it.
Go through the list of a's, adding UUIDs to the list.
$("tr input[checked=checked]").parent().parent().find("td a").each(function(){
listOfUUIDs.push(
$(this).prop('href').substr(indexOf("uuid=") + 5)
)
});

This should give you what you need.
$('tr').each(function(index) {
var $this = $(this),
input = $this.find('input'),
result = '';
if ( input.is(':checked') ) {
var uuid = $this.find('a').attr('href').replace(/^\/Home\/DeviceDetails\?uuid=/g, ""),
result = result + index + '. ' + input.attr('id') + ' has the uuid: ' + uuid + '<br />';
}
$('#result').html(result);
});

try this
$( "input[type=checkbox]" ).change(function() {
if($(this).is(":checked")) {
alert($(this).attr("id"));
}
});

Related

Select and change input value in table using data-attribute and JavaScript

I have a table with input fields, and I would like to fill this fields with some data, that users can change if they like.
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data.calcname + '"]')[0];
//And now, try to select the input in each row, but I can't get it to work..:
//var myInput = myRow.find("input:text")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
However, I have trouble selecting the various input fields, in order to fill them out, as shown in the snippet.
I guess there is an easy jQuery syntax to do this, but despite my best efforts, I have not been able to find it.
How can I achieve this?
You can, in a cleaner way, iterate over the data array with Array.prototype.forEach() and execute a provided function once for each array el element.
The rest is jQuery.
Code:
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
data.forEach(function(el) {
$('tr[data-calcname="' + el.calcname + '"]').find('input:text').val(el.value);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data[i].calcname + '"]').find("input").val(data[i].value);
//And now, try to select the input in each row, but I can't get it to work..:
//var myInput = myRow.find("input:text")
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
Use attribute selector to select the td. By combining with data[i].calcname to get the desired, with .find() to get the input.
Set the value using .val()
You need to write you selector of the tr like this var myRow = $('tr[data-calcname="' + data[i].calcname + '"]')
In your case data[i] would be: data[0] = ({"calcname" : "calc1", "value" : 5}) data[1] = ({"calcname" : "calc2", "value" : 10})
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myRow = $('tr[data-calcname="' + data[i].calcname + '"]');
var myInput = myRow.find("input:text").val(data[i].value);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
As data is an array i.e. data[i], use index to access the elements, also there is no need use [0] which returns the reference to DOM element.
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
for (var i = 0; i < data.length; i++) {
var myRow = $('[data-calcname="' + data[i].calcname + '"]');
var myInput = myRow.find("input:text");
myInput.val(data[i].value)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr data-calcname="calc1">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
<tr data-calcname="calc2">
<td>
SomeName
</td>
<td>
SomeDescription
</td>
<td>
<input type="text">
</td>
</tr>
</table>
You set up a for loop correctly but now you need to use your index i to access the desired element in your array data: data[i].calcname
You don't need to get the row but you need to get the input inside that row: $('[data-calcname="' + data[i].calcname + '"] td input')
You change a textfield's title by setting its value property: myInput.value = "new value"
//Server side processing gives me an array like:
var data = [];
data.push({"calcname" : "calc1", "value" : 5});
data.push({"calcname" : "calc2", "value" : 10});
//The data array may not have data for all the rows, and the order of items may not be the same.
//For each data item, I select the appropriate row:
for (var i = 0; i < data.length; i++) {
var myInput = $('[data-calcname="' + data[i].calcname + '"] td input')[0];
myInput.value = data[i].value
}
The for of loop
If you don't understand step 1. Maybe it is simpler to use the for of loop:
for (let element of data) {
var myInput = $('[data-calcname="' + element.calcname + '"] td input')[0];
myInput.value = element.value
}

Selecting data out of the nth td element

I'm attempting to get the data("borgid") out of the following html:
<tr style="cursor:default;" class="odd">
<td class=" ">1</td>
<td class=" ">What was your favorite childhood pet's name?</td>
<td data-borgid="1" class=" ">Generic Hospital Networks</td>
<td class=" ">5173</td>
<td style="text-align:right;" class=" "><input type="button" value="Remove" name="1" class="deleteMeCQ" style="cursor:pointer;"></td>
</tr>
I have tried both $(':nth-child(2)', $(this)).data("borgid") and $tds.eq(2).data("borgid"). Both return "undefined". Thanks in advance.
See also: Is there a way to combine $(this) with :nth-child?
var a = [];
$("#ChallengeQuestionsTable tbody tr").each(function () {
var $tds = $(this).children('td');
var questionid = '';
var question = '';
var borgid = '';
if ($tds.length == 5) {
questionid = $tds.eq(0).html();
question = $tds.eq(1).html();
borgid = $(':nth-child(2)', $(this)).data("Borgid");
a.push('{ "questionid" : "' + questionid + '", "question" : "' + question + '", "borgid" : "' + borgid + '" }');
}
});
If you want to get borgid, you can select by existing attribute:
borgid = $($(this).find("[data-borgid]").get(0)).attr("data-borgid");
In general if you want to select the nth td you could go with
$("td:eq(1)")
e.g. to select the second td.
If you want to iterate over all <tr> and its <td> and say, you want to select the 2nd one, you would do it as follows:
$("tbody").find("tr").each(function(){
$(this).find("td:eq(1)").html("changed")
};
Here is a Fiddle to play with. And here is the documentation of :eq().
Does this work, if you grab the data by an attribute selector?
var borgid = $(this).find("td[data-borgid]").data("borgid");
It could also be beneficial to avoid ":nth-child", shall you change your HTML later.

i need to get the second td span value based on tr id how can i get that?

i need to get the second td span value based on tr id
`
<table><tr id="1">
<td style="width:150px;"><span id="1">C </span></td>
<td><span style="width:800px;">hello world</span></td>
<td><input type="checkbox" name="1" onclick="KeywordText(1);" value="1"></td>
</tr>
<tr id="2">
<td style="width:150px;"><span id="2">Dot Net </span></td>
<td><span style="width:800px;">Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai,Dot Net,java,cobol,hai</span></td>
<td><input type="checkbox" name="2" onclick="KeywordText(2);" value="2"></td>
</tr></table>
This assumes you want the second span
JavaScript:
var row = document.getElementById("rowId");
var spans = row.getElementsByTagName("span");
var secondSpan = spans[1];
jQuery:
var secondSpan = $("#rowId span:eq(1)");
It you want the span inside the second table cell
JavaScript:
var row = document.getElementById("rowId");
var cells = row.getElementsByTagName("td");
var spans = cells.getElementsByTagName("span");
var secondSpan = spans[0];
or with querySelector
var span = document.getElementById("rowId").querySelector("td + td > span");
jQuery:
var secondSpan = $("#rowId td:eq(1) span");
And spans do not have a value, you either what its html or its text.
JavaScript:
var text = secondSpan.innerHTML;
jQuery:
var text = secondSpan.html(); // or secondSpan.text();
function KeywordText(id) {
var td = document.getElementById(id).cells[1];
console.log(td.firstChild.innerHTML); // "hello word" if id == 1
}
example: http://jsfiddle.net/n2t4Z/
Strictly speaking, you can do it like this:
getSpanValueByRowId(1);
function getSpanValueByRowId(rowID) {
var row = document.getElementById(rowID);
var cells = row.getElementsByTagName("td");
var span = cells[1].getElementsByTagName("span")[0];
return span.innerText;
}
Although you could use jQuery to get it, it would look like this:
function getSpanValueByjQuery(rowID){
return $("#"+rowID + " td:nth-child(2) span").text();
}
Using jQuery:
var getvalue=$(this).closest('tr').find('td:eq(1) span').val();
alert(getvalue);

How to append new rows to a table more than once?

I have a table within a form that I want to append new rows as the user enters input in the last row of the table.
$('table.form-table').on('input', function() {
var tableID = '#' + $(this).closest('table').attr('id');
if(jQuery(this).closest('tr').is(':last-child')) {
var currTR = $(this).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = jQuery(currTRhtml);
var checkBox = jQuery('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
jQuery(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
And the html code if needed (simplified/trimmed):
<table class="form-table" id="XXX" border="1" cellspacing="0" cellpadding="3">
<thead>
<tr class="main"><th nowrap colspan="3" align="left"
class="border-left border-top border-right">
<h3>XXX</h3></th>
</tr>
<tr>
<th>header</th>
</tr>
</thead>
<tbody>
<tr>
<input type="hidden" name="isnew" value="">
<td >
<input type="text"
name="new_text"
value="">
</td>
</tr>
</tbody>
</table>
The problem is that this works only once and does not continue appending new rows. It's as if the last-child filtering does not get reset...
Any thoughts?
The problem is that you need to use the event's target, rather than "this". Right now "this" refers to the current table, but you need to refer to the current input box and then use closest() to find its parent tr (and :first-child to make sure it's the last one). So your code needs to look more like this:
$('table.form-table').on('input', function(e) {
var tableID = '#' + $(this).closest('table').attr('id');
if ($(e.target).closest('tr').is(':last-child')) {
var currTR = $(e.target).closest('tr');
var currTRhtml = '<tr>' + currTR.html() + '</tr>';
var nextRow = $(currTRhtml);
var checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
Notice I'm passing the event as "e" and then referencing the current input box with $(e.target).
Here's a working JS fiddle.
I suspect the problem is that you need to delegate the input event as the appended rows do not exist on $(document).ready(). Try doing something like this to delegate the handler:
$(document).ready(function () {
$('table.form-table tbody').on('input', 'tr', function () {
var self = $(this),
tableID = '#' + self.closest('table').attr('id'),
currTR = self.closest('tr'),
currTRhtml = '<tr>' + currTR.html() + '</tr>',
nextRow = $(currTRhtml),
checkBox = $('<td class="border-right checks"><input type="checkbox" name="del_000" value="000"></td>');
if (currTR.is(':last-child')) {
$(tableID).append(nextRow);
checkBox.appendTo(currTR);
}
});
});
Fiddle: http://jsfiddle.net/KW7ET/

Javascript for each instead of multiple if

Please, give "direction where to go"
Many input rows. For each row is field class="row_changed"
If value in the field is higher than 0, then ajax pass entire row to php. Each row is included in <tr> </tr> For each <tr> id is set <tr id='row'>
At the moment I can do it only with many if
Need something like: if value in any of field field class="row_changed" is more than 0, then pass corresponding row (inside <tr id='row'>) to php.
Here is some information. Is it suitable for the described case?
<tr id='row1'>
<td>
<input type="text" name="row1[]" id="date_day1" class="row_changed1">
</td>
...
<td>
<input type="text" name="row1[]" id="is_row_changed1" size="1">
<script>
$(".row_changed1").on("change", function () {
document.getElementById('is_row_changed1').value = 1;
});
</script>
</td>
<tr>
if ($("#is_row_changed1").val() > 0) {
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
});
var str = $("#row1 :input").serialize();
$("#load1_1").text(str);
}
if ($("#is_row_changed2").val() > 0) {
$.post("_autosave_array.php", $("#row2 :input").serialize(), function (data2) {
$('#load2').html(data2);
$('#is_row_changed2').val(0)
});
var str = $("#row2 :input").serialize();
$("#load2_1").text(str);
}
Something like this should do it:
function doPost(changedRowId,serializeRowId,resultId,serializeResultId){
if ($(changedRowId).val() > 0) {
$.post("_autosave_array.php", $(serializeRowId + ":input").serialize(), function (data2) {
$(resultId).html(data2);
$(changedRowId).val(0)
});
var str = $("#row2 :input").serialize();
$(serializeResultId).text(str);
}
var rowData = [{changedRowId: "#is_row_changed1", serializeRowId: "#row1", resultId: "#load1", serializeResultId: "#load1_1"},
{changedRowId: "#is_row_changed2", serializeRowId: "#row2 ", resultId: "#load2". serializeResultId: "#load2_1"}
];
for(var i = 0; i < rowData.length; ++i){
var data = rowData[i];
doPost(data.changedRowId,data.serializeRowId,data.resultId,data.serializeResultId);
}
I can see that all your input tags have the same name, you can select all of them by name then put your condition/logic inside
sample:
$("input[name='row1[]']").each(function(){
if($(this).val()>0){
$.post("_autosave_array.php", $("#row1 :input").serialize(), function (data1) {
$('#load1').html(data1);
$('#is_row_changed1').val(0)
}
});

Categories