How to alter table row value which is inserted dynamically using Jquery? - javascript

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());
});

Related

Bootstrap tags input is not working with new dynamically added table rows with jquery

Bootstrap tagsinput is not working with new dynamically added rows. Actually I am cloning a hidden table row which contains some input fields and a icon. On click of that icon, modal form appears and on submit of that modal form, I set some values from that modal form into input bootstrap tagsinput field that is contained in that row. Please note that all rows have same input fields but that have different tr row ids and input tagsinput field ids. When I try to set value in bootstrap tagsinput field for any dynamically added row, value is always set against hidden tr row, I don't know why this is happening with tagsinput. I tried to set value for other input fields (textfield, numberfield) but they are working fine. What's the issue with this?
$('.table-add').click(function () {
// var $tr = $TABLE.find('tr.hide');
// var $clone = $tr.clone(true).addClass('hide table-line');
// $tr.removeClass('hide table-line');
var $clone = $TABLE.find('tr.hide').clone(true).removeClass('hide table-line');
hid = $TABLE.find('tr.hide').attr('id');
// //Assigning every table row a unique ID
var max=0;
$('table').find('tr').each(function(){
var id=parseInt($(this).attr('id'));
if (id>=max){
max = id;
}
});
//cloning row with new ID
$clone.attr('id', parseInt(max)+1);
$clone.find('input.myinput').attr('id', parseInt(max)+1);
$clone.appendTo( $('#'+hid).parent() );
});
Every table row has these ( tagsinput field and modalform field).
<td>
<span id="modelbox" data-target="#myModal" href="#myModal" data-toggle="modal" class="glyphicon glyphicon-plus"></span>
</td>
<td>
<input contenteditable="false" name="unique_tag"
class = "myinput" id="tagsinputid" data-role="tagsinput"/>
</td>
When modal form button is clicked, Following code works, in which I get parent tr row and get row Id that is unique and save it for another action and populate modal form with some words.
//Click on model box
$('tr #modelbox').click(function() {
var $row = $(this).closest('tr');
var tbid = $row.attr('id'); // table row ID
$('#myModal').data('current', tbid); //save current tbid
var fieldOption = []
$row.find('#words option').each(function() { fieldOption.push($(this).val()); });
console.log(fieldOption);
$('.modal-body-inner').html('');
for(var i = 0, size = fieldOption.length; i < size ; i++){
var item = fieldOption[i];
$('.modal-body-inner').append("<span class=span1 > "+ item + "</span>");
}
});
On click of modal form, I do take table row and set value against tagsinput field for that table row which is not working in my case. This is not working for tagsinput field I don't know why but it is working for other input fields. When I set value in tagsinput for that row, this code set value for tagsinput field for hidden row.
$('#modelformbuttonclick').click(function() {
var tableRowId = $('#myModal').data('current');
c = '#' + tableRowId;
//removing all tags if anyone updates tags
$(c+ ' input.myinput').tagsinput('removeAll');
var count=1; var color = ["Europe","America","Australia","Africa","Asia", "Asia2", "Africa2"];
$('.modal-body-inner span.myclass').each(function() {
c = '#' + tableRowId;
var randomNumber = Math.floor(Math.random()*color.length);
$(c + ' input.myinput').tagsinput('add', { "name": "tagsdata", "value": $(this).text() , "text": $(this).text(), "continent": color[randomNumber]});
count = count+1;
});
submitForm();
});

How to select the particular list box item using Jquery?

I want to select one of the list box item when user select the table row.
The last item user added SupplierCode to a table by clicking ADD Button. When user want to modify the records from table, once they click that particular row, the value should move to FilterValue and Field in the list box should select that particular Field Name which is selected by user.
Now user select the first row to modify the value. That value is moved to FilterValue textbox, But list box item is not selected automatically to StoreID
But when I check the code in browser. it shows selected for that particular item which item user wants to select, but the color is not changed.
This is my code
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(')', '');
alert(FieldName + ' ' + Values);
$("#FilterField option[value=" + FieldName + "]").attr("selected", true);
$("#txtFilterValue").val(Values);
});
try with following code and check if it works
//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(')', '');
//alert(FieldName + ' ' + Values); provided your FieldName as correct value
$("#FilterField").val(FieldName);
$("#txtFilterValue").val(Values);
});

jQuery - Get table cell value

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);

Remove a row from Html table based on condition

I have a html table
<TABLE id="dlStdFeature" Width="300" Runat="server" CellSpacing="0" CellPadding="0">
<TR>
<TD id="stdfeaturetd" vAlign="top" width="350" runat="server"></TD>
</TR>
</TABLE>
I am dynamically adding values to it as :
function AddToTable(tblID, value)
{
var $jAdd = jQuery.noConflict();
var row= $jAdd("<tr/>").attr("className","lineHeight");
var cell = $jAdd("<td/>").attr({"align" : "center","width" : "3%"});
var cell1 = $jAdd("<td/>").html("<b>* </b>" + value);
row.append(cell);
row.append(cell1);
$jAdd(tblID).append(row);
}
Now I want a function to remove a row from this table if the value matches..as
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
remove this row
}
}
Here VALUE is TEXT ..which needs to be matched..If exists need to remove that row,,
try this
function RemoveFromTable(tblID, VALUE){
$("#"+tblID).find("td:contains('"+VALUE+"')").closest('tr').remove();
}
hope it will work
Try like this
function RemoveFromTable(tblID, VALUE)
{
If(row value = VALUE)
{
$("TR[id="+VALUE+"]").hide(); //Assumes that VALUE is the id of tr which you want to remove it
}
}
You can also .remove() like
$("TR[id="+VALUE+"]").remove();
I highly recommend using a ViewModel in your case. So you can dynamically bind your data to a table and conditionally format it to whatever you like. Take a look at Knockout.js: http://knockoutjs.com/
function RemoveFromTable(tblID, VALUE){
$(tblID).find('td').filter(function(){
return $.trim($(this).text()) === VALUE;
}).closest('tr').remove();
}
Remove row from HTML table that doesn't contains specific text or string using jquery.
Note: If there are only two column in HTML table, we can use "last-child" attribute to find.
*$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:last-child");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: If there are more than two column in HTML table, we can use "nth-child(2)" attribute to find.
Passing column index with "nth-child(column index)"
$(document).ready(function(){
$("#tabledata tbody .mainTR").each(function(){
var lastTD = $(this).find("td:nth-child(2)");
var lastTdText = lastTD.text().trim();
if(!lastTdText.includes("DrivePilot")){
$(this).remove();
}
});
});
Note: "DrivePilot" is nothing but text or string

How to dynamically add a new column to an HTML table

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:

Categories

Resources