Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have code in the following style :
<tr id="201461">
<td id="0A" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 23 2008">Feb 23 2008</td>
<td id="0B" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 25 2008">Feb 25 2008</td>
<td id="0C" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="Feb 28 2008">Feb 28 2008</td></tr><tr id="201460">
<td id="1A" style="cursor:pointer" onClick = "ProcessTextBoxClick()" value="47">47</td></tr>
I have some JQuery where I am getting the id of each row, and now I want to get each value in each td for each row. How do I do this?
var tbl = document.getElementById("tbl-1");
var numRows = tbl.rows.length;
for (var i = 1; i < numRows; i++) {
var ID = tbl.rows[i].id;
Your code does not look like jQuery. Are you sure you aren't using the term jQuery as a synonym to JavaScript? :) If that is the case, I suggest you read this question as well; it will make things a lot more clear for you.
Anyway, here goes JavaScript:
var tbl = document.getElementById("tbl-1");
var numRows = tbl.rows.length;
for (var i = 1; i < numRows; i++) {
var ID = tbl.rows[i].id;
var cells = tbl.rows[i].getElementsByTagName('td');
for (var ic=0,it=cells.length;ic<it;ic++) {
// alert the table cell contents
// you probably do not want to do this, but let's just make
// it SUPER-obvious that it works :)
alert(cells[ic].innerHTML);
}
}
Alternatively, if you really use jQuery:
var table = $('#tbl-1').
var rowIds = [];
var cells = [];
$('tr', table).each(function() {
rowIds.push($(this).attr('id'));
$('td', $(this)).each(function() {
cells.push($(this).html());
});
});
// you now have all row ids stores in the array 'rowIds'
// and have all the cell contents stored in 'cells'
in jQuery:
$("table#tbl-1 tr").each(function( i ) {
$("td", this).each(function( j ) {
console.log("".concat("row: ", i, ", col: ", j, ", value: ", $(this).text()));
});
});
You can check it in work here: http://jsfiddle.net/3kWNh/
I want to get each value in each td for each row
Do you want the value of the value attribute, the HTML, or the HTML stripped of markup? The various answers so far have mostly gone with "the HTML", at least one went with "the HTML stripped of markup", but none (so far) has gone with "the value of the value attribute". So:
Using jQuery:
var valuesByRowID = {};
$("#tbl-1 tr").each(function() {
valuesByRowID[this.id] = $(this).find("> td").map(function() {
// Option 1: Getting the value of the `value` attribute:
return this.getAttribute("value"); // or return $(this).attr("value");
// Option 2: Getting the HTML of the `td`:
return this.innerHTML;
// Option 3: Getting the HTML of the `td` with markup stripped:
return $(this).text();
}).get();
});
The end result is an object with properties for each row, with the property name being the row's id value, and the property value being an array of the td information.
So for instance, to get the array for row 201461, you can do this:
var data = valuesByRowID["201461"]; // Note that property names are strings
var index;
for (index = 0; index < data.length; ++index) {
alert(data[index]);
}
The above uses:
$() to find the rows in the table.
map (followed by get) to build the array of values.
A simple JavaScript object to hold the result. JavaScript objects are, at heart, maps (aka dictionaries, aka associative arrays, aka name/value pair collections).
Off-topic:
As I mentioned in a comment on the question, the HTML you've listed there is "invalid" in W3C terminology, td elements don't have a value attribute. You might consider using data-* attributes instead.
As Spudley pointed out in a comment on the question, those id values are likely to cause you trouble. Recommend not having id values that start with a digit. Although valid in HTML5, they're not valid in earlier versions of HTML and not valid in CSS. Since jQuery uses CSS selectors, if you're using CSS, I would strongly advise sticking to the CSS rules. (In your case, it's really easy: Just put an d on the front of them or seomthing.)
You can simply do
$("td","#tbl-1").each(function(){
//access the value as
$(this).html()
});
What you are using there is not jQuery, if you are using jQuery you can use .html(); to retrieve the value.
Here is your code with jQuery:
$('#tbl-1 td').each(function(){
var ID = $(this).attr('id');
var value = $(this).html();
});
If you want to loop over all <td>
$('#tbl-1 td').each(function() {
// do stuff for each td in here...
alert($(this).html());
})
NOTE: This is jQuery whereas your example is native JavaScript.
Related
I'm not the best at using jQuery, but I do require it to be able to make my website user-friendly.
I have several tables involved in my website, and for each the user should be able to add/delete rows. I created a jquery function, with help from stackoverflow, and it successfully added/deleted rows. Now the only problem with this is the names for those input fields is slightly messed up. I would like each input field to be an array: so like name[0] for the first row, name[1] for the second row, etc. I have a bunch of tables all with different inputs, so how would I make jQuery adjust the names accordingly?
My function, doesn't work completely, but I do not know how to go about changing it.
My Jquery function looks like:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
clone.find('select').each(function(i) {
$(this).attr('name', $(this).attr('name') + i);
});
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount = $(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
I also created a jsFiddle here: https://jsfiddle.net/tareenmj/err73gLL/.
Any help is greatly appreciated.
UPDATE - Partial Working Solution
After help from a lot of users, I was able to create a function which does this:
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
clone.find("select").val('');
clone.find('input').each(function() {
var msg=$(this).attr('name');
var x=parseInt(msg.split('[').pop().split(']').shift());
var test=msg.substr(0,msg.indexOf('['))+"[";
x++;
x=x.toString();
test=test+x+"]";
$(this).attr('name', test);
});
clone.find('select').each(function() {
var msg1=$(this).attr('name');
var x1=parseInt(msg1.split('[').pop().split(']').shift());
var test1=msg1.substr(0,msg1.indexOf('['))+"[";
x1++;
x1=x1.toString();
test1=test1+x1+"]";
$(this).attr('name', test1);
});
tr.after(clone);
});
A working jsFiddle is here: https://jsfiddle.net/tareenmj/amojyjjn/2/
The only problem is that if I do not select any of the options in the select inputs, it doesn't provide me with a value of null, whereas it should. Any tips on fixing this issue?
I think I understand your problem. See if this fiddle works for you...
This is what I did, inside each of the clone.find() functions, I added the following logic...
clone.find('input').each(function(i) {
// extract the number part of the name
number = parseInt($(this).attr('name').substr($(this).attr('name').indexOf("_") + 1));
// increment the number
number += 1;
// extract the name itself (without the row index)
name = $(this).attr('name').substr(0, $(this).attr('name').indexOf('_'));
// add the row index to the string
$(this).attr('name', name + "_" + number);
});
In essence, I separate the name into 2 parts based on the _, the string and the row index. I increment the row index every time the add_row is called.
So each row will have something like the following structure when a row is added...
// row 1
sectionTB1_1
presentationTB1_1
percentageTB1_1
courseTB1_1
sessionTB1_1
reqElecTB1_1
// row 2
sectionTB1_2
presentationTB1_2
percentageTB1_2
courseTB1_2
sessionTB1_2
reqElecTB1_2
// etc.
Let me know if this is what you were looking for.
Full Working Solution for Anyone Who needs it
So after doing loads and loads of research, I found a very simple way on how to do this. Instead of manually adjusting the name of the array, I realised that the clone method will do it automatically for you if you supply an array as the name. So something like name="name[]" will end up working. The brackets without any text has to be there. Explanation can't possible describe the code fully, so here is the JQuery code required for this behaviour to work:
$(document).ready(function() {
$("body").on('click', '.add_row', function() {
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
var clone = tr.clone();
clone.find("input").val('');
tr.after(clone);
});
$("body").on('click', '.delete_row', function() {
var rowCount =
$(this).closest('.row').prev('table').find('tr.ia_table').length;
var tr = $(this).closest('.row').prev('table').find('tr.ia_table:last');
if (rowCount > 1) {
tr.remove();
};
});
});
A fully working JSfiddle is provided here: https://jsfiddle.net/tareenmj/amojyjjn/5/
Just a tip, that you have to be remove the disabled select since this will not pass a value of null.
I am trying to remove an element based on type of attribute. It isn't working for some reason.
The element in question is this:
<p style="width:250px;font-size:11px;text-align:left;margin-left:1.2ex;margin-top:0px;margin-bottom:0px;line-height:1.15em;">– in Europe<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green & dark grey</span>)<br>
– in the European Union<span style="font-size:8px;"><span style="white-space:nowrap;"> </span></span>(<span style="font-size:9px;">green</span>)</p>
I am trying to remove it this way - item is a container element.
$(item).find("p").filter("[style]").remove();
There are no other <p> tags with the attribute style, however this doesn't appear to remove it.
Other code, like this, works fine:
$(item).find(".reference").remove();
How do I remove all p tags with the style attribute from the item element?
This is how item is created:
$.get(link, function(response) {
var elements = $.parseHTML(response);
var wiki = $(elements).find('#mw-content-text').find("p");
//var ps = [];
var arrayLength = wiki.length;
for (var i = 0; i < arrayLength; i++) {
if (wiki[i].innerHTML === "") {
break;
}
var item = wiki[i];
The link variable is a link to wikipedia.
Maybe try this:
$.each(item.children('p'), function(index) {
if ($(this).attr('style')) {
$(this).remove();
}
});
item refers to p element itself. you don't have to find p in item:
$(item).filter("[style]").remove();
after re-looking over your question ,
$(item).find("p").filter("[style]").remove();
is perfectly valid , instead of trying to come up with alternative ways to write it , find out what is wrong with item, because it is not what you think it is if above code is not working
Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
I have a solution already, but it's messy and could use some tweaking. Basically, I have two tables on a page and each table has an input text box for every column with a corresponding filter name. The idea is that while the user is typing above that column, the table is being filtered by each variable. This is where I found my solution, but this is only for one input box, and one table. Also when you clear the input box, the entire table clears. I like that this example isn't case sensitive, but it has a few bugs. http://www.marceble.com/2010/02/simple-jquery-table-row-filter/ Here's a jsfiddle that I put together, yet it isn't filtering as it should. http://jsfiddle.net/anschwem/mAAvW/
Code:
<script>
$(document).ready(function() {
//Declare the custom selector 'containsIgnoreCase'.
$.expr[':'].containsIgnoreCase = function(n,i,m){
return jQuery(n).text().toUpperCase().indexOf(m[3].toUpperCase())>=0;
};
$("#searchInput").keyup(function(){
$("#fbody").find("tr").hide();
var data = this.value.split(" ");
var jo = $("#fbody").find("tr");
$.each(data, function(i, v){
//Use the new containsIgnoreCase function instead
jo = jo.filter("*:containsIgnoreCase('"+v+"')");
});
jo.show();
}).focus(function(){
this.value="";
$(this).css({"color":"black"});
$(this).unbind('focus');
}).css({"color":"#C0C0C0"});
});
</script>
HTML:
<table>
<thead>
<tr>
<td><input value="Animals"></td>
<td><input value="Numbers"></td>
</tr>
</thead>
<tbody>
<tr><td>cat</td><td>one</td></tr>
<tr><td>dog</td><td>two</td></tr>
<tr><td>cat</td><td>three</td></tr>
<tr><td>moose</td><td>four</td></tr>
<tr><td>mouse</td><td>five</td></tr>
<tr><td>dog</td><td>six</td></tr>
</tbody>
</table>
You can do something like this, I didn't reuse any of the code you had. I explained in mines what it's doing though.
$("th input[type=text]").keyup(function () {
var reg = new RegExp(this.value, 'i'); // <-- regex case insensitive
var ind = $(this).closest('th').index(); // index of th - so we know which side to filter
var tds = $('tr').find('td:eq(' + ind + ')'); // get the corresponding td's
var match = tds.filter(function (i, v) {
return reg.test($(v).text()); // return only td's that match
});
tds.not(match).css('visibility', 'hidden'); // hide ones that don't match
match.css('visibility', 'visible'); // show matching
});
FIDDLE
I do not understand it exactly.
I did some simple example, with only one column test:
$(document).ready(function() {
$("input[name=Animals]").keydown(function() {
setTimeout(function() {
$("td:first", "tbody>tr").each(function() {
lookfor = $("input[name=Animals]").val();
if (new RegExp(lookfor, "i").test($(this).text()))
$(this).parent().show();
else
$(this).parent().fadeOut();
}, 0);
});
});
});
p.s.
If you use key tracking handle keydown and then let browser to update by setTimeout(yourjob,0). It has better feeling for user.
http://jsfiddle.net/mAAvW/19/
hmm , here is my solution ...
without a regex more of a simple solution using the same stuff you used
as long as you have search boxes have the same class name this will be prefect
$(document).ready(function() {
var column ;
$(':input').focus(function(){
column = $(this).parent('td').index();
column = column+1;
console.log(column); //logs number of the column
})
$('.search').keyup(function(){
var v = $(this).val();
if(v.length == 0) {
$('#fbody tr td:nth-child('+column+')').show();
}else{
console.log(v.length);
$('#fbody tr td:nth-child('+column+')').not( $('#fbody tr td:nth-child('+column+')').filter("*:contains('"+v+"')")).hide();
$('#fbody tr td:nth-child('+column+')').filter("*:contains('"+v+"')").show();
}
})
});
Suppose I have a form with 20 rows as shown in the figure below:
I'm naming the elements in the each row as:
1st row (Ambiance) -> v1[requirement], v1[observation], v1[status], v1[remarks]
2nd row (TV Room) -> v2[requirement], v2[observation], v2[status], v2[remarks]
3rd row (Cleanliness) -> v3[requirement], v3[observation], v3[status], v3[remarks]
.... and so on till 20th row
Using jquery or javascript can I find the number of rows present based on the names of the element? i.e., in this form name starts from v1 and ends at v20. So there are 20 rows.
UPDATE
The reason why I want the number of rows is because I plan to process the forms using:
for($i=1; $i<=$rowcount; $i++)
{
$v.$i = $_POST['v'.$i];
// then insert the first row into table and so on
}
If there is always a header row, then the number of rows will be the number of tr elements in the table -1, Eg.
var rowCount = $("#myTable tr").length -1;
This saves you having to use some convoluted method of attribute selector or string parsing.
This approach should work for you:
var rowCount = $("#data-table tr").filter(function() {
return $(this).find('[name^="v"]').length;
}).length;
This code will count only tose rows which have input with the name starting with v. I guess this is what you need.
Quick demo: http://jsfiddle.net/dfsq/2P5cN/
UPD
As per Mark Reed's comment we can make it even more simple:
var rowCount = $('#data-table tr').has('[name^=v]').length;
If you can't modify the markup at all, then you'll pretty much have to loop over everything and do your own counting. Something like this:
var tds = document.getElementsByTagName('td'); // or just $('td') for jQuery
var count_tds = tds.length;
var max = 0;
for (var i=0; i<count_tds; ++i) {
var td = tds[i]
var m = td.id.match(/^v(\d+)\[/)
if (m) {
if (m[1] > max) max=m[1]
}
}
Now max is the number of rows, assuming there are no extraneous elements with id's that match the pattern.
http://jsfiddle.net/usDD7/1/
EDIT Clearly I wasn't thinking with jQuery. See dfsq's answer for a much better solution (and my comment on that answer for a tiny improvement).
I have a requirement of changing all dropdown values in all the rows in a tale based on master dropdown. say someone selects "value 2" in dropdown1, dropdown2 values in all the rows in the table should show "value2".
function change(){
var cid = document.frm.locdropdown.selectedIndex;
document.frm.locdropdown2.selectedIndex = cid;
}
is the java script I use to change it but this changes only first row.
please help..
From your example code it looks like you've given the same ID to all your locdropdown2 elements? Maybe you should post an example of your table HTML. It's normal practice to give unique IDs to elements, so you may want to test the NAME attribute instead, but anyway something like the following should work:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var inputs = document.getElementsByTagName("input");
for (var i=0, l = inputs.length; i < l; i++) {
if (inputs[i].id == "locdropdown2")
inputs[i].selectedIndex = cid;
}
}
Another option is to loop through each row in the table. The following example assumes your locdropdown2 inputs are the only thing in the third column, but you can adapt to suit your actual layout:
function change() {
var cid = document.frm.locdropdown.selectedIndex;
var tableRows = document.getElementById("yourTableId").tBodies[0].rows;
for (var i=0, l=tableRows.length; i < l; i++) {
tableRows[i].cells[2].firstChild.selectedIndex = cid;
}
}
Note: I haven't actually tested any of that code, but it should be more than enough to get you started and you can tweak as needed. (You can use Google to learn about tBodies, rows, cells, firstChild, etc.)