I have two rows of a table here. When I click the checkbox in the first table row, I'm trying to target the ID of the span in the next table row. I have an alert in my code just to show me that I was successful.
What I have isn't working. I can't figure out a way to select data in the next table row when the checkbox in the first row is clicked.
<table>
<tr id="row-a">
<td>
<input type="checkbox">
<span>
some text
</span>
</td>
</tr>
<tr>
<td>
<span id="target">
some text
</span>
</td>
</tr>
</table>
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $("tr#row-a').next('tr').find('span').attr('id');
alert(spanID);
});
});
Try this:
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = $(this).closest('tr').next().find('span').attr('id');
alert(spanID);
});
Example fiddle
$(document).ready(function() {
var myCheck = $("tr#row-a td input");
myCheck.change(function(){
var spanID = myCheck.parents("tr").next().find('span').attr('id');
alert(spanID);
});
});
The change was in this line:
var spanID = myCheck.parents("tr").next().find('span').attr('id');
Which does the following:
Finds the checkbox's tr parent
Gets the next sibling node (next tr)
Finds the span
Gets its id
Related
I'm trying to run through a table and change each cell based on the row. Table example:
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
Function example (in script under body):
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
$(document).load(myFunction);
The example shown is non-specific version of the actual function I'm trying to run.
To be clear, I have linked to the jQuery 2.1 CDN, so the page should be able to read jQuery.
Console shows no errors, but still does not run appear to run the function. Checking the tested row in the console shows no change to the html in the div. Any advice for this?
When I run it I get an error on r.find() because .find() is a jQuery function and needs to be called on a jQuery object, which r is not. Simply wrapping it in a $() works.
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
}
https://jsfiddle.net/k50o8eha/1/
You may need to do asomething similar to the c.getChild();
Here's a simplified version :
$("#myTable tr").each(function(i, r){
if(i==1)
{
$(this).find('td').each(function()
{
$(this).find("div").html("html here");
});
}
});
Example : https://jsfiddle.net/DinoMyte/4dyph8jh/11/
Can you give this a try...
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = r.find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = c.getChild();//attempt to get the div in the td
square.innerHTML='html here';
});
}
});
});
or shorthand...
$(function() {
});
$( document ).ready(function() {
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i, r){
var cells = $(r).find('td');
if(i==1){//to edit second row, for example
cells.each(function(j,c){
var square = $(c).children('div');
square.text('html here');
});
}
});
});
table{
background-color: #eee;
width: 300px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id='myTable'>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
<tr>
<td><div id='A1'></div></td>
<td><div id='A2'></div></td>
</tr>
</table>
This works, you can try this
JSBIN
function myFunction(){
var table = $('#myTable');
var rows = table.find('tr');
rows.each(function(i){
if(i==1){//to edit second row, for example
$(this).find('td').each(function(j){
$(this).find('div').html('html here');
});
}
});
}
$(document).ready(myFunction);
first the "id" should be unique to an element... but ok, this should do the trick:
$(document).ready(function(){
$("#myTable>tr:odd").children("div").text('html here');
});
If you want to put html code in the div, change text for html. if you want to specify the row then:
$(document).ready(function(){
myRow = //set its value...
$("#myTable>tr").each(function(idx, element){
if(idx == myRow){
element.children("div").text('html here');
}
}, myRow);
});
I have a table and I am deleting the table rows using the following script:
$("#ordertable tr input:checked").parents('tr').remove();
Then I am updating the table ids as follows:
function updateRowCount(){
var table = document.getElementById("ordertable");
var rowcountAfterDelete = document.getElementById("ordertable").rows.length;
for(var i=1;i<rowcountAfterDelete;i++) {
table.rows[i].id="row_"+i;
table.rows[i].cells[0].innerHTML=i+"<input type='checkbox' id='chk_" + i + "'>";
var j = i+1;
$("#ordertable tr:nth-child("+j+")").find("td").eq(1).find("select").attr("id","pn_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(2).find("input").attr("id","notes_"+i);
$("#ordertable tr:nth-child("+j+")").find("td").eq(3).find("input").attr("id","qty_"+i);
table.rows[i].cells[4].id = "pdctid_"+i;
}
}
I need a condition in such a way that user can not allow to delete last row.
I mean in deletion If user marked last row checkbox then I should get an alert.
It seems you want to not delete the last row with a checked checkbox. So you'd get the row to be deleted, then get the row with the last checked checkbox. If they're the same row, don't delete. Otherwise, delete.
The following is just an example of putting the above algorithm to the test. Of course there is much to improve to suit your circumstance.
E.g.
function deleteRow(el) {
// Get the row candidate for deletion
var row = el.parentNode.parentNode;
// Get last checked checkbox row, if there is one
var table = row.parentNode.parentNode;
var cbs = table.querySelectorAll('input:checked');
var cbRow = cbs.length? cbs[cbs.length - 1].parentNode.parentNode : null;
// If the row to be deleted is the same as the last checked checkbox row
// don't delete it
if (row === cbRow) {
alert("Can't touch this...");
// Otherwise, delete it
} else {
row.parentNode.removeChild(row);
}
}
<table>
<tr>
<td>0 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>1 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
<tr>
<td>2 <input type="checkbox">
<td><button onclick="deleteRow(this)">Delete row</button>
</table>
I'm using mvc, I want to get the value of each and every td to edit in my table
<table>
<tr>
<td id="val"></td>
</tr>
</table>
<input type="button" value="" class="edit"/>
And in the javascript am using
var td = $(document).getElementById("val").innetHTML;
$(document).on('click', '.edit', function (e) {
if(td == null)
{
}
else
code......
})
But whenever am clicking the row edit button it is returning only the first row value, not getting the value of second and further.
Any suggestion will be greatly appreciated.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('.edit').click(function()
{
$('table td').each(function() {
var val = $(this).html();
alert(val);
});
});
});
</script>
You have to use 'class' attribute instead 'id':
<table>
<tr><td class="editVal"></td></tr>
<tr><td class="editVal"></td></tr>
<tr><td class="editVal"></td></tr>
</table>
You have to use JQuery for iterate each element:
$('.editVal').each(function(i) {
// get value
var $td = $(this).html;
// set value
$(this).html = 'Nuovo valore';
}
If you are trying to get the values of a table one by one, I think jquery each is the function for you.
There is also another question in SO with a good example.
I am new to javascript.
Can anyone help me to implement an onclick event on click of a HTML table row created through javascript?
Kindly note that I am inserting the data in table cells using innerHTML.
Below is the code snippet of what i have tried.?
Java Script function:
function addRow(msg)
{
var table = document.getElementById("NotesFinancialSummary");
var finSumArr1 = msg.split("^");
var length = finSumArr1.length-1;
alert("length"+ length);
for(var i=1; i<finSumArr1.length; i++)
{
var row = table.insertRow(-1);
var rowValues1 = finSumArr1[i].split("|");
for(var k=0;k<=10;k++)
{
var cell1 = row.insertCell(k);
var element1 = rowValues1[k];
cell1.innerHTML = element1;
}
}
for(var i=1; i<rowCount; i++)
{
for(var k=0;k<=10;k++)
{
document.getElementById("NotesFinancialSummary").rows[i].cells[k].addEventListener("click", function(){enableProfileDiv()}, false);
}
}
}
HTML table code in jsp :
<TABLE id="NotesFinancialSummary" width="800px" border="1" align="left" >
<tr >
<th>Symbol</th>
<th>Claimant</th>
<th>MJC</th>
<th>S</th>
<th>Type</th>
<th>Indemnity Resv</th>
<th>Indemnity Paid</th>
<th>Medical Resv</th>
<th>Medical Paid</th>
<th>Legal Resv</th>
<th>Legal Paid</th>
</tr>
<tr>
<td>
</td>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
<TD> </TD>
</tr>
</table>
<table id="table"></table>
$("#table").append("<tr><td>Hi there</td></tr>");
$("#table").on( "click", "tr", function(){
// do something
alert( $(this).children("td:first").text() );
});
Any time the click event bubbles up to <table id="table">, this function will be called (no matter if the <tr>s are inserted dynamically, or hard coded).
This will require the jQuery library
http://jquery.com/
http://api.jquery.com/on/
One way to do it would be using document.createElement
Instead of doing:
yourParentElement.innerHTML = "<tr>Something</tr>";
You can do
var tr = document.createElement("tr");
tr.innerHTML = "Something";
tr.onclick = function() {
//code to be executed onclick
};
yourParentElement.appendChild(tr);
Another way, would be to use an id (only if you're doing this once, you don't want duplicated ids):
yourParentElement.innerHTML = "<tr id='someId'>Something</tr>";
document.getElementById("someId").onclick = function() { //fetch the element and set the event
}
You can read more about events here, but just so you have an idea onclick will only let you set one function.
If you want a better solution you can use something like addEventListener, but it's not crossbrowser so you may want to read up on it.
Lastly, if you want to set up an event on every tr you can use:
var trs = document.getElementByTagName("tr"); //this returns an array of trs
//loop through the tr array and set the event
after you insert your <tr> using innerHTML, create a click event listener for it.
document.getElementById("the new id of your tr").addEventListener("click", function() {
what you want to do on click;
});
Something like this: http://jsfiddle.net/gnBtr/
var startEl = document.getElementById('start');
var containerEl = document.getElementById('container');
var inner = '<div id="content" style = "background: pink; padding:20px;" > click on me </div>'
// Function to change the content of containerEl
function modifyContents() {
containerEl.innerHTML = inner;
var contentEl = document.getElementById('content');
contentEl.addEventListener("click", handleClickOnContents, false);
}
// listenting to clikc on element created via innerHTML
function handleClickOnContents() {
alert("you clicked on a div that was dynamically created");
}
// add event listeners
startEl.addEventListener("click", modifyContents, false);
Check it out:
$('#your_table_id tbody').on('click', 'tr', function (e) {
$('td', this).css('background-color', 'yellow');
} );
css:
tr:hover td{
background-color: lightsteelblue !important;
}
It works fine for me, specially when I'm using jquery dataTable pagination.
I want to get each cell value from an HTML table using JavaScript when pressing submit button.
How to get HTML table cell values?
To get the text from this cell-
<table>
<tr id="somerow">
<td>some text</td>
</tr>
</table>
You can use this -
var Row = document.getElementById("somerow");
var Cells = Row.getElementsByTagName("td");
alert(Cells[0].innerText);
function Vcount() {
var modify = document.getElementById("C_name1").value;
var oTable = document.getElementById('dataTable');
var i;
var rowLength = oTable.rows.length;
for (i = 1; i < rowLength; i++) {
var oCells = oTable.rows.item(i).cells;
if (modify == oCells[0].firstChild.data) {
document.getElementById("Error").innerHTML = " * duplicate value";
return false;
break;
}
}
var table = document.getElementById("someTableID");
var totalRows = document.getElementById("someTableID").rows.length;
var totalCol = 3; // enter the number of columns in the table minus 1 (first column is 0 not 1)
//To display all values
for (var x = 0; x <= totalRows; x++)
{
for (var y = 0; y <= totalCol; y++)
{
alert(table.rows[x].cells[y].innerHTML;
}
}
//To display a single cell value enter in the row number and column number under rows and cells below:
var firstCell = table.rows[0].cells[0].innerHTML;
alert(firstCell);
//Note: if you use <th> this will be row 0, so your data will start at row 1 col 0
You can also use the DOM way to obtain the cell value:
Cells[0].firstChild.data
Read more on that in my post at http://js-code.blogspot.com/2009/03/how-to-change-html-table-cell-value.html
You can get cell value with JS even when click on the cell:
.......................
<head>
<title>Search students by courses/professors</title>
<script type="text/javascript">
function ChangeColor(tableRow, highLight)
{
if (highLight){
tableRow.style.backgroundColor = '00CCCC';
}
else{
tableRow.style.backgroundColor = 'white';
}
}
function DoNav(theUrl)
{
document.location.href = theUrl;
}
</script>
</head>
<body>
<table id = "c" width="180" border="1" cellpadding="0" cellspacing="0">
<% for (Course cs : courses){ %>
<tr onmouseover="ChangeColor(this, true);"
onmouseout="ChangeColor(this, false);"
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');">
<td name = "title" align = "center"><%= cs.getTitle() %></td>
</tr>
<%}%>
........................
</body>
I wrote the HTML table in JSP.
Course is is a type. For example Course cs, cs= object of type Course which had 2 attributes: id, title.
courses is an ArrayList of Course objects.
The HTML table displays all the courses titles in each cell. So the table has 1 column only:
Course1
Course2
Course3
......
Taking aside:
onclick="DoNav('http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp?courseId=<%=cs.getCourseId()%>');"
This means that after user selects a table cell, for example "Course2", the title of the course- "Course2" will travel to the page where the URL is directing the user: http://localhost:8080/Mydata/ComplexSearch/FoundS.jsp . "Course2" will arrive in FoundS.jsp page. The identifier of "Course2" is courseId. To declare the variable courseId, in which CourseX will be kept, you put a "?" after the URL and next to it the identifier.
I told you just in case you'll want to use it because I searched a lot for it and I found questions like mine. But now I found out from teacher so I post where people asked.
The example is working.I've seen.
Just simply.. #sometime when larger table we can't add the id to each tr
<table>
<tr>
<td>some text</td>
<td>something</td>
</tr>
<tr>
<td>Hello</td>
<td>Hel</td>
</tr>
</table>
<script>
var cell = document.getElementsByTagName("td");
var i = 0;
while(cell[i] != undefined){
alert(cell[i].innerHTML); //do some alert for test
i++;
}//end while
</script>
<td class="virtualTd" onclick="putThis(this)">my td value </td>
function putThis(control) {
alert(control.innerText);
}
I found this as an easiest way to add row . The awesome thing about this is that it doesn't change the already present table contents even if it contains input elements .
row = `<tr><td><input type="text"></td></tr>`
$("#table_body tr:last").after(row) ;
Here #table_body is the id of the table body tag .
Here is perhaps the simplest way to obtain the value of a single cell.
document.querySelector("#table").children[0].children[r].children[c].innerText
where r is the row index and c is the column index
Therefore, to obtain all cell data and put it in a multi-dimensional array:
var tableData = [];
Array.from(document.querySelector("#table").children[0].children).forEach(function(tr){tableData.push(Array.from(tr.children).map(cell => cell.innerText))});
var cell = tableData[1][2];//2nd row, 3rd column
To access a specific cell's data in this multi-dimensional array, use the standard syntax: array[rowIndex][columnIndex].
Make a javascript function
function addSampleTextInInputBox(message) {
//set value in input box
document.getElementById('textInput').value = message + "";
//or show an alert
//window.alert(message);
}
Then simply call in your table row button click
<td class="center">
<a class="btn btn-success" onclick="addSampleTextInInputBox('<?php echo $row->message; ?>')" title="Add" data-toggle="tooltip" title="Add">
<span class="fa fa-plus"></span>
</a>
</td>