How to access text from neighboring table cell? - javascript

I have a set of search results presented in a table. Each row has a radio box. Once the user has selected a row I would like to access the description text from the neighboring cell.
Using jQuery or straight javascript, what is the best way to do this?
<tr class="odd">
<td class="chosenCode"><input type="radio" value="123" name="chosenCode"></td>
<td class="codeFound">123</td>
<td class="descriptionFound">This is description text for code 123</td>
</tr>
Thanks

$("table input:radio").change(function () {
alert( $(this).closest("tr").children(".descriptionFound").text() );
});
Or, more elaborate:
// prepare once
$("table input:radio").each(function () {
var descr = $(this).closest("tr").children(".descriptionFound").text();
$(this).data("descr", descr);
});
// use
$("table input:radio").change(function () {
alert( $(this).data("descr") );
});

Inside the event callback function you can use this code to get the content of the description element.
$(this).next('.descriptionFound').text();

Related

How to compare several td.text() in tr using jQuery

<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
Here I have a table with a tr in it and 4 td's.
Now, my question is, how can I compare the td.text() with the other one?
For example:
a loop that takes the text of first td and then compare it with other td's.
If it is the same, then give that td a class.
HERE: td id="td1" should get a class
BUT:
When I'm at the 3e td, the 3e td should get a class.
This code should work for you:
var tds;
$('tr').each(function(i, item){
tds = $(this).find('td');
tds.each(function(j, elem1){
tds.each(function(k, elem2){
if($(elem1)[0] != $(elem2)[0] && $(elem1).text() == $(elem2).text()){
$(elem1).addClass('cl');
}
});
});
});
FIDDLE: https://jsfiddle.net/lmgonzalves/cqa6m6va/1/
You can use this code:
function setClasses(word) {
var tds = $("tr td");
for(var i = 0; i < tds.length; i++) {
if(tds.eq(i).text() === word) {
tds.eq(i).addClass('red');
}
}
}
setClasses("test1");
jQuery selectors will be your friend here. :)
var $container = $("#tr")
$container.children().each(function() {
if (!($(this).hasClass("td")) {
var sTextVal = $(this).text();
var $currTextGroup = $container.children(":contains('" + sTextVal + "')");
if ($currTextGroup.length > 1) {
$currTextGroup.addClass("td");
}
}
});
I'll explain the logic, and then touch on one issue to be aware of . . .
Basically, this code:
Collects all of the the children of the <tr> and loops through them one at a time
If the current child does not already have a class of "td" (if it already has a "td" class, then this text has already been checked for duplicates), it retrieves the text from inside the element and searches for all of the children of the <tr> that contain that same text value
If more than one of the children in the <tr> contain that text, all of those children are given the class of "td"
The one potential issue that this solution could run into is if the text in the current element is present as part of the text in one of its siblings. For example, if the text in one sibling is "the", and it has some siblings that have text values of "then" and "there" and "the end", they will be found by :contains.
If your text values are sufficiently "patterned" (as they are in your example), though, this should not be an issue. If it is an issue, there is a more complex way to do that "common text" selection, but I won't bother with that, unless it is necessary.
If I understand correctly, you want to select the first 'td' in a 'tr' and compare it against the other 'td' in your table. Please try the below code and let me know if it works for you.
HTML (provided by OP)
<table>
<tr id="tr1">
<td id="td1"> test1 </td>
<td id="td2"> test2 </td>
<td id="td3"> test1 </td>
<td id="td4"> test3 </td>
</tr>
</table>
CSS
.color--red { color: red; }
jQuery
$(document).ready(function(){
var first = $("#tr1 :first-child").html();
$('#tr1 :not(:first-child)').each(function() {
if(first == $(this).html()){
$(this).addClass("color--red");
}
});
});
I tried to keep it as simple as possible. The variable first pertains to that first 'td' that you want to use for comparison. Note how the each function operates on 'all elements except the first child in the tr', which clearly will omit the first variable we declared initially. From there it's all about comparing using $(this).html() to grab the value of the currently selected element, against the value obtained from the first variable.
Once this succeeds, simply add a class of your choice. For simplicity's sake, I added my own color--red class to the mix, which should show red color text for the third 'td' element as you suggested in your question post. Enjoy! Let me know if you need anything further.

jquery, remove table row when unchecked

I have a table with rows of data, when a user clicks on the row (tr) or the checkbox, it appends that row of data into another location. How do I make it that when a user unchecks from the original table AND the new appended row, that the row disappears?
I want it so that when the user unchecks from the original table, the appended row disappears. When the user unchecks from the appended row, only the appended row disappears.
// original table
<div id="searchsub">
<table class="showsub">
<tr class="datarow">
<td>data</td>
<td>data</td>
<td>data</td>
</tr>
</table>
</div>
Row appends to this new table:
<table id="datarow">
</table>
Here's the jquery I have:
$(document).ready(function() {
$("#searchsub table tr").click(function(event) {
if(event.target.type !== 'checkbox') {
$(":checkbox", this).trigger("click");
}
});
$i = 1;
$("input[type='checkbox']").change(function(e) {
if($(this).is(":checked")) {
$(this).closest("tr").addClass("highlightrow");
var datarow = $(this).closest("tr.datarow");
var row = datarow.clone();
row.addClass("append" + $i);
$("#submitshipment #datarow").append(row);
$i++;
} else {
$(this).closest("tr").removeClass("highlightrow");
$(".append").closest("tr").remove();
}
})
})
Of course this way whenever the row is unchecked ALL of the rows are deleted, which isn't what I want. Please help?
EDIT: mark up of the appended row:
<tr class="datarow highlightrow append1">
<td>120093</td>
<td>G13</td>
<td><input type="checkbox" class="searchsub" name="searchsub[]" value="1"></td>
</tr>
jsFiddle:
http://jsfiddle.net/7cXqR/1/
Yes, unfortunately the non-functional jsFiddle doesn't really help ;-)
I think I've sorted out what you're trying to do though; the issue is you don't have anything (be it using jQ .data() or in markup) that relates your appended rows to your source rows. If you look at the jsFiddle I made (forked from yours) you'll see how I use the "value" attribute you have on the checkbox in the source table to find the cloned rows in the append table:
$('#datarow').find('input:checkbox[value="' + $(this).val() + '"]').closest('tr').remove();
http://jsfiddle.net/A4w59/
This approach could be modified to use any markup (stock or custom data-* attributes) or even jQ's .data() method; the key is being able to associate the source & append rows so that you can remove the appended row when unselecting it in the source table.

using each method in jquery

I have a table which has input checkboxes.
When user selects checkbox I'm saving this value attribute to an array...so the user is clicking, checking and unchecking and after some time he will press the button.
In the button click event I'm trying to iterate through each of the records and check if the each input[type="checkbox"] has the same value as the one in the array, so if the values are the same then I will read all the td values from that row.
This is my code:
$('#something').click(function(){
$( "tr td input" ).each(function(index) {
//selected is an array which has values collected from the checked checkboxes..for example [2,3]
for(var i=0;i<selected.length;i++)
{
if($(this).val()==selected[i][0].value)
{
alert($('tr').eq(index).find('td').eq(1).text());
}
}
});
});
And html code:
<table>
<tbody>
<tr>
<td><input type="checkbox" value="on"></td>
<td>ID</td>
<td>Name</td>
</tr>
<tr>
<td><input type="checkbox" value="0"></td>
<td>1</td>
<td>John</td>
</tr>
<tr>
<td><input type="checkbox" value="1"></td>
<td>2</td>
<td>Steve</td>
</tr>
</tbody>
</table>
So for example if I have value [1] in the array. How can I get all the row information from that? My code is not working. Any idea?
I created a plunk that iterates over each input, reads the values and writes them to an array:
var checkBoxCollection = new Array();
var cb = {};
$("button").click(function(){
$("input").each(function(index, el){
id = $(el).attr("id");
val = $(el).val();
isChecked = $(el).is(':checked');
console.log(index, id, val);
checkBoxCollection.push({'id': id, 'val': val, 'isChecked': isChecked});
}); // each
console.log(checkBoxCollection);
}); // button.click
You could use this way to select the cell value as soon as the button is clicked and would only have to test if the box was checked. To learn how to use the console and the chrome dev tools you may take a look at this 7 minute video
Update with one checkbox for all
In my updated plunk you can see that i use two different selectors
// using different selector - see my comment and tell me if you can not do that
Select all <input class="cbAll" type="checkbox" id="cbAll" value="on">
// and each checkbox like this
<input class="cb" type="checkbox" id="cb0" value="0">
And the javascript
$("input.cbAll").click(function(){
$("input.cb").each(function(index, el){
// javascript ternary operator is optional this switches each checked state
$(el).is(':checked')
? $(el).prop('checked', false)
: $(el).prop('checked', true);
}); // each
});
Update including the copy of the text inside the <td>
In this plunk the text from the cells in the same tablerow of the checbox is copied into the array. The relevant code are these lines
isChecked = $(el).is(':checked');
if(isChecked){
var cells = $(el).parent().parent().children();
var cellId = cells.eq(1).text();
var cellName = cells.eq(2).text();
checkBoxCollection.push({'id': id, 'val': val
, 'isChecked': isChecked
, 'cellId': cellId
, 'cellName': cellName});
console.log(index, id, val, cellId, cellName);
}
In the screenshot you can see that the values of each checked textbox are copied.
As far as i can tell i solved all your questions:
use of jquery each to iterate over checkboxes
copy the text of cells within a tablerow into an array if the checkbox of that row is checked
If i understood your questions not fully please clarify what you would like to know.
It appears that the condition if($(this).val()==selected[i][0].value) is not true.
If it is a simple array, you don't need .value in the end. Simply compare with selected[i][0]
if($(this).val()==selected[i][0])

Getting inner tag element inside an "each"

I've been messing around with different forms and tables, now I need something that takes data from table tr and td field, runs a if statement on each fetched item, and outputs text inside the form, depending what was found in td fields.
So right now I have something like this, which doesn't do anything useful at all, for now, just outputs td-01 class values into the form:
var test;
$('tbody tr').each(function(index) {
test = $(this+'.td.td-0');
$('fieldset.csc-mailform').after($('td.td-0'));
});
and my table structure looks something like this:
<table class="contenttable contenttable-3 tabel">
<tr class="tr-even tr-0">
<td class="td-0">01</td>
<td class="td-1">Valik 1</td>
<td class="td-last td-2">150€</td>
</tr>
<tr class="tr-odd tr-1">
<td class="td-0">01</td>
<td class="td-1">Valik 2</td>
<td class="td-last td-2">50€</td>
</tr>
<tr class="tr-even tr-2">
<td class="td-0">01</td>
<td class="td-1">Valik 3</td>
<td class="td-last td-2">170€</td>
</tr>
<tr class="tr-odd tr-3">
<td class="td-0">01</td>
<td class="td-1">Valik 4</td>
<td class="td-last td-2">88€</td>
</tr>
</table>
Right now it only find tr tags and outputs all of them. I need it to split the tr tag up, run if condition on td-0 to determine if it needs to be radio button/text input/checkbox etc, then see what td-1 contains and make that field name, then td-2 is for example a price. all of this should end up in a form.
So as you can see, I am stuck with jQuery, but I think it should be doable.
edit:
I got something like this after messing around a little, but my if statements don't seem to work on jQuery objects, any way to get around this?
var check1;
$('tbody tr').each(function(index) {
//test = $(this+'.td.td-0');
check1 = $('td.td-0');
alert(check1);
if(check1=='01'){
content_type="checkbox";
}else if(check1=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type);
//$('fieldset.csc-mailform').after($('td.td-0'));
});
//edit2
Ugh, I was running if statement against jQuery object, of course it didn't work.
I got it working with this, looks quite nasty, but it seems to work:
$('tr').each(function () { var val = $(this).children('td:first').text();
//$check1 = $('td.td-0');
if(val=='01'){
content_type="checkbox";
}else if(val=='02'){
content_type="text";
}else{
content_type="none";
}
$('fieldset.csc-mailform').after(content_type + '<br/>');
}
);
Now, I need to figure out how to create input fields from these.
You could possibly make it a bit cleaner by using the jQuery selector context, e.g.:
$('tr').each(function () {
var val = $('td:first', this).text();
..
}
Something like this will do:
$('table tr').each(function() {
$tds = $(this).children();
for(var i=0;i<$tds.length;i++){
$td = $tds[i];
if($td.hasClass('td-0'){
//do your thing by getting next TD or something else
break;
}
}
});

Jquery conditional statement

My html
<tr id="uniqueRowId">
<td>
<input class="myChk" type="checkbox" />
</td>
<td class="from">
<textarea class="fromInput" ...></textarea>
</td>
<td class="to">
<textarea ...></textarea>
</td>
</tr>
I have a table where each row is similar to the above with only one exception: not all rows will have textreas. I need to grab all rows that have textareas AND checkbox is not "checked".
Then I need to leaf through them and do some stuff.
I tried something like:
var editableRows = $("td.from .fromInput");
for (s in editableRows)
{
$s.val("test value");
}
but it didn't work.
1) how do I grab ONLY the rows that have checkboxes off AND have fromInput textareas?
2) how do I leaf through them and access the val() of both textareas?
I am sure this could be optimized, but I think it will work.
$("tr:not(:has(:checked))").each(function(i, tr) {
var from = $(tr).find("td.from textarea").val();
var to = $(tr).find("td.to textarea").val();
//now do something with "from" and "to"
});
See it working on jsFiddle: http://jsfiddle.net/RRPqb/
You can use this to select the rows:
$('tr', '#yourTable').has('input:checkbox:not(:checked)').has('textarea')
Live demo: http://jsfiddle.net/simevidas/Zk5EH/1/
As you can see in the demo, only the row that has a TEXTAREA element and a unchecked checkbox will be selected.
However, I recommend you to set classes to your rows: the TR elements that contain TEXTAREA elements should have a specific class set - like "directions". Then you could select those rows easily like so:
$('tr.directions', '#yourTable').each(function() {
if ( $(this).find('input:checkbox')[0].checked ) return;
// do your thing
});
$("tr:not(:has(:checked)):has(input.fromInput)")
Should be what you need. All the rows that don't have anything checked but that do have an input with the class 'fromInput'
If you want to loop through them to get the value of any textarea just extend your selector:
$("tr:not(:has(:checked)):has(textarea.fromInput) textarea")
Or as above if you want to be able to distinguish them:
$("tr:not(:has(:checked)):has(textarea.fromInput)")
.each(function() {
var from = $(this).find("td.from textarea").val();
var to = $(this).find("td.to textarea").val();
})
I don't know how much performance is a concern here, but if it is, then rather then writing a selector to find rows that contain a textarea you may find it helps to add a class to the row itself.
<tr class="hasTextarea">
Then you could alter your JQuery as so:
$("tr.hasTextarea:not(:has(:checked))")

Categories

Resources