I have a table which looks like the following. The price normally comes from a database this is just for showing the problem I have.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" name="tickets" id="tickets" class="amount" maxlength="2" autocomplete="off"></td>
<td>Ticket:</td>
<td class="price">20,50</td>
<td class="sub_total"></td>
</tr>
</table>
What I would like to do is: when the user types a number in the field tickets it should update the field sub_total. With the jQuery I have this is not working. When I alert(price) I get undefined. So I wonder how to make the sub_total field with auto updated values. It might also be interesting to know that I have more rows like this beneath this row. So the script should only update the field from one specific row at a time.
What I already tried but without success:
How to get a table cell value using jQuery;
How to get a table cell value using jQuery?;
How to get table cell values any where in the table using jquery
Thanks in advance.
You need to do traverse back up to the parent tr element before you try to find the .sub_title or .price elements.
$(document).ready(function() {
$(document).delegate('.amount input[type="text"]','keyup',(function() {
var $this = $(this);
var $tr = $this.closest("tr");
var sub_total = $tr.find('.sub_total');
var price = $tr.find('.price').text();
var amount = $this.val();
alert(price);
}));
});
Change you code like this
$(document).ready(function() {
$(document).on('input[type="text"].amount', 'keyup', (function() {
var $this = $(this);
var sub_total = $this.closest("tr").find('.sub_total');
var price = $this.closest("tr").find('.price').text();
var amount = $this.val();
alert(price);
}));
});
find() will search for the children. So you should get into the parent tr first before using find().
You can use closest("tr") to get the parent tr element
It's because price and sub_total are not children of the current element (as find is selecting):
var sub_total = $this.find('.sub_total');
var price = $this.find('.price').text();
they are siblings of its parent or more simply children of the container tr.
Try instead:
var sub_total = $this.closest('tr').find('.sub_total');
var price = $this.closest('tr').find('.price').text();
example for a
<table id="#myTable">
I write this:
function setCell( idTab, row, col, text) {
var idCel = idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
$(idCel).html(text);
}
function getCell( idTab, row, col ) {
var idCel =idTab + " tbody tr:nth-child(" + row + ") td:nth-child(" + col + ")";
return $(idCel).html();
}
setCell( "#myTab", 3, 4, "new value" );
alert( getCell("#myTab", 3, 4);
Related
I am looping through a grids datasource and when it gets to ToFactory not being empty I need to add a div into its td cell. Below is the code that I am using to get the td at index 18 of its row
var data = this.dataSource.view();
for(i=0;i<data.length;i++){
var dataItem = data[i];
var tr = $("#QuickEntryGrid").find("[data-uid='" + dataItem.uid + "']");
if(dataItem.ToFactory != ""){
let me = tr.find('td')[18];
me.innerHtml = "<div class='abc'>1234</div>"; // Doesn't work
console.log(me);
}
}
the variable me is
<td class role='gridcell'></td>
and what I would like to put in the td is
<div class='abc'>123</div>
and me should look like this
<td class role='gridcell'><div class='abc'>123</div></td>
but its not happening,
any idea's on why I am not getting this working? I have also tried
me.append("<div class='abc'>123</div>");
I want to alter HTML Table row which is inserted by dynamically.
At beginning there will no rows in table.
HTML Code
<table class="table table-hover " id="queryTable">
<thead>
<tr>
<th>Field Name</th>
<th>Values</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
JQUERY Code
//SELECT Table ROW
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});
Those 3 records are added dynamically. When user wants to modify the value of any FieldName of Values ,Once user click that row from the table, the value will show on Filter Value textbox as you can see above.
In the above pic, User select second row. once the user change the value in textbox and when they click the Change button the second row should alter.
Assuming your table id as YOURTABLEID and your textbox id as FILTERVALUETEXTBOX
var td;
$(document).on("click","#YOURTABLEID td",function(){
td=$(this);
$("#FILTERVALUETEXTBOX").val($(this).text());
});
If you want to click on tr and want to get second td value, then
var td;
$(document).on("click","#YOURTABLEID tr",function(){
td=$(this).find("td:last"); //AS SECOND TD IS LAST
$("#FILTERVALUETEXTBOX").val(td.text());
});
Once you get your td value in textbox, Change button click event will be as follow
$("#btnChange").click(function(){
td.text($("#FILTERVALUETEXTBOX").val());
});
UPDATE
var td;//THIS IS MISSING IN YOUR CODE
$(document).on("click", '#queryTable tbody tr', function () {
var tr = $(this);
td=$(this).find("td:last");//THIS IS MISSING IN YOUR CODE
var FieldName = tr.find("td:first").text();
var Values = tr.find("td:last").text();
FieldName = FieldName.replace('AND ', '');
FieldName = FieldName.replace('OR ', '');
Values = Values.replace('IN(', '');
Values = Values.replace(')', '');
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values); //FilterValue textbox id
});
$("#btnChange").click(function () {
td.text($("#txtFilterValue").val());
});
<tbody id="contacttable">
</tbody>
<script>
var hrtypeCode = document.getElementById('hrtypeCode').value;
var hrCode = document.getElementById('hrCode').value;
var hrName = document.getElementById('hrName').value;
var hrDesc = document.getElementById('hrDesc').value;
for(i=0;i<hrCode.length; i++){
if(hrCode[i]!="") {
var table = document.getElementById("contacttable");
var slNo = table.rows.length;
var tr = table.insertRow(slNo-1);
tr.id = 'list_tr_' + slNo;
tr.innerHTML ='<td><input type="text" name="hrtypeCode" value="'+hrtypeCode[i]+'" ></td><td><input type="text" name="hrCode" value="'+hrCode[i]+ '"></td><td><input type="text" name="hrName" value="'+hrName[i]+'" ></td>';
count++;
}
}
</script>
<i>
how to find out the cell values.i have tried the following code but it showing entire TD row
tbl.rows[i].cells[j].innerHTML);
alert(tbl.rows[i].cells[j].innerHTML);
Kindly help in finding the value.. thanks.
Table cells don't have values, only input elements do. You need to access the <input> element within the table cell.
Use:
tbl.rows[i].cells[j].getElementsByTagName("input")[0].value
DEMO
I've a form in which containing one <div> tag and the HTML within it. This is what I've when page loads. Then through AJAX I'm appending the same block(i.e. ) to the existing one. In every <div> tag there is one <table> and in that <table> I've a button with class products. After clicking on it I'm calculating the no. of rows present in that table only and assigning the id to the newly added row. But the issue I'm facing is when I add multiple such tables using AJAX and click on add button of any table it's calculating the total no. of rows present in all tables and adding that much no. of rows to the table in which I clicked add button. This shouldn't have to happen. It has to add only one row. I've created a jsfiddle for your reference. In fiddle I've put in static HTMl so it's working fine over there but on my local machine when I add multiple tables using AJAX I'm getting wrong no. of rows added.For example if I added three tables and click on add button of first table then it's adding four rows to that table. Why it's counting the total no. of rows present in all the tables present on a page?Is there any need to improve my script? My script is as follows:
$(document).ready(function() {
$('.products').click(function () {
var table_id = $(this).closest('table').attr('id');
var no = table_id.match(/\d+/)[0];
//var first_row = $(this).closest('table').find('tbody tr:first').attr('id');
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
var tbody = $('tbody', '#'+table_id);
var n = $('tr', tbody).length + 1;
new_row.attr('id', 'reb' + no +'_'+ n);
$(':input', new_row).not('.prod_list').remove();
$('select', new_row).attr('name','product_id_'+no+'['+n+']');
$('select', new_row).attr('id','product_id_'+no+'_'+n);
$('<button style="color:#C00; opacity: 2;" type="button" class="close delete" data-dismiss="alert" aria-hidden="true">×</button>').appendTo( $(new_row.find('td:first')) );
tbody.append(new_row);
$('.delete').on('click', deleteRow);
});
});
Following is jsFiddle link: http://jsfiddle.net/vrNAL/2/
I think what you mean to query is this:
var tbody = $('#' + table_id + ' tbody');
Instead of:
var tbody = $('tbody', '#' + table_id);
From the jQuery documentation, I don't think selectors work this way.
You are doing some strange things with the IDs here. why are you getting the IDs and selecting the sleemts with that, instead of using the selected elements directly?
Example:
var table_id = $(this).closest('table').attr('id');
var table = $("#" + table_id);
Is the same as just
var table = $(this).closest('table');
and
var first_row = $('#'+table_id).find('tbody tr:first').attr('id');
var new_row = $('#'+first_row).clone();
is the same as:
var new_row = table.find('tbody tr:first').clone();
I have a table to which I am currently dynamically adding rows: http://jsfiddle.net/fmuW6/5/
Now I'd like to add a new column to the table as well with a click of a button. The user will enter the column header in a textbox.
How can I achieve this? If the user adds 4 rows, the Add a new Column button should take care of all the existing rows (adding checkbox in each one).
update
I'm looking to add column name and checkbox at row level.
so I've added the text box in which the user will input the column name: http://jsfiddle.net/fmuW6/10/
<input type=text placeholder='columnname'/>
<button type="button" id="btnAddCol">Add new column</button></br></br>
so then when user clicks the button the columnname should be the value in the textbox and at the row level should be checkboxes. So basically the new column should be appended to all tr in the table except the first row since that is the column names
I updated your fiddle with a small example how you could do that.
jsFiddle - Link
var myform = $('#myform'),
iter = 0;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
if(trow.index() === 0){
trow.append('<td>Col+'iter+'</td>');
}else{
trow.append('<td><input type="checkbox" name="cb'+iter+'"/></td>');
}
});
iter += 1;
});
This would add a new column to every row, including an count-variable that gets applied to the first row as name and to the name-attribute of the checkboxes on the following rows.
Consider using th - elements for the table header, that way you wouldn't need the index-check i'm making and it would be more semantically correct.
I left out the part where the user would put in a name for the column, but as you see, you could just replace the iter - value with that in the end.
Modern pure JavaScript solution:
const addColumn = () => {
[...document.querySelectorAll('#table tr')].forEach((row, i) => {
const input = document.createElement("input")
input.setAttribute('type', 'text')
const cell = document.createElement(i ? "td" : "th")
cell.appendChild(input)
row.appendChild(cell)
});
}
document.querySelector('button').onclick = addColumn
<table id="table">
<tr><th><input type="text" value="test 1" /><th/></tr>
<tr><td><input type="text" value="test 2" /><td/></tr>
</table>
<button type="button">add column</button>
First row will contain a th instead of td. Each new cell contains a input. Feel free to change this to suit your need.
The answer works, but still here is an alternative way where we use thead and tbody !
JS
$('#irow').click(function(){
if($('#row').val()){
$('#mtable tbody').append($("#mtable tbody tr:last").clone());
$('#mtable tbody tr:last :checkbox').attr('checked',false);
$('#mtable tbody tr:last td:first').html($('#row').val());
}
});
$('#icol').click(function(){
if($('#col').val()){
$('#mtable tr').append($("<td>"));
$('#mtable thead tr>td:last').html($('#col').val());
$('#mtable tbody tr').each(function(){$(this).children('td:last').append($('<input type="checkbox">'))});
}
});
Use this code for adding new column:
$('#btnAddCol').click(function () {
$("tr").append("<td>New Column</td>");
});
But you need to change the value for the first row with a text and others to include a <input type="checkbox" />. And it is better to
Check it out jsFiddle .............................
http://jsfiddle.net/fmuW6/8/
$(document).ready(function () {
$('#btnAdd').click(function () {
var count = 3, first_row = $('#Row2');
while(count-- > 0) first_row.clone().appendTo('#blacklistgrid');
});
$('#btnAddCol').click(function () {
$("#blacklistgrid tr").each(function(){
$(this).append("<td>test</td>");
})
});
});
Using a table of 4 columns:
I can add values dinamically like this:
var TableId = "table_" + id;
var table = $("#" + TableId );
table.find("tbody tr").remove();
table.append("<tr><td>" + "1" + "</td><td>" + "lorem" + "</td><td>" + "ipsum" + "</td><td>" + "dolor" + "</td></tr>");
and the final result will be: