Add data dynamically to a table row - javascript

This problem is related to my previous question in this link. Now, what I'm trying to do is do the opposite thing. I have here a dynamic table (where you can add and delete rows) and whatever is the data that the user input in the latest use of table (trigger by a button) should be retrieve and be posted in the same table (if the same button is clicked).
Here's the code that I used to get the data from my dynamic table:
$('#tableSearchMainAccount1 tr').each(function(){
var td = '';
if ($(this).find("td:first").length > 0) { // used to skip table header (if there is)
$(this).find('option:selected').each(function(){
td = td + $(this).text()+ ',';
});
td = td + $(this).find('input').val();
filt[ctr]=td;
ctr += 1;
}
});
alert (filt); //alert output like name,equals,ann,age,equals,11
Now, what I want to do is that when I click the button again, this previous input data will be posted again in my dynamic table.
My table is something that looks like this:
<table> <tr><th>field</th><th>comparison</th><th>value</th></tr>
<tr>
<td>
<select style="width:5em;" class="field">
<option>name</option>
<option>age</option>
<option>sex</option>
</select>
</td>
<td>
<select style="width:5em;" class = "comp">
<option>equals</option>
<option>starts with</option>
<option>not equal to</option>
</select>
</td>
<td><input type="text" class = 'value'></td>
<td><img class="add" src="css/images/add.png" /></td> // this is used to add new row
</tr>
</table>
The last data that a user input in the table should be displays in the table when table shows again. How do I add the data to my dynamic table?
EDIT:
When the button is clicked, a dialog opens which contains my dynamic table and every time a user close the dialog, all the row from that table will be gone same as the data the user entered. I already create a variable that holds the latest inputted data in the table. So when the button click again, I want the table to generate or displays the last input data by the user. The output should be the same as the latest input data.

Assuming you had a button id add and you wanted to add a table row onto the end:
$('#add').on('click', function() {
var $lastTr = $('table tr:last');
$lastTr.clone().insertAfter($lastTr);
$('#add', $lastTr).remove();
});
Using .clone to help us clone the last row, and appending it at the end.
Fiddle: http://jsfiddle.net/garreh/w9fXJ/
And just to pre-empt you're next question, here's the addition of removing a row ;-)
$('.remove_row').on('click', function() {
$(this).closest('tr').remove();
});
Fiddle: http://jsfiddle.net/garreh/w9fXJ/1/

JQuery.prepend and JQuery.append will help you

Related

Xpath clicking button within a td where row contains a specific text vlaue

I'm currently using Nightwatch to do some automated tests, but CSS selectors were extremely complex and did not do the job for me. I've instead started to look at XPath to do the job however the table in question is fairly complex.
I want to be able to .click() a button within a td value, where that specific row in the table contains a specific value. The table looks like this:
Username Email Display Name Buttons to Click (1st one wanted)
test test#example test (1st button)(2nd button)
test2 test2#example test (1st button)(2nd button)
Each of these values are within a tr > td so being able to find it is proving difficult. This is my currently XPath:
.click('/table[#id="admin-user-list"]/tbody/tr[td = "test2"]/td/button')
The HTML tree looks like this:
<div id>
<div class>
<table class>
<tbody>
<tr>
<td data-bind>(username)
<td data-bind>(email)
<td data-bind>(display name)
<td button>
(1st button)
(2nd button)
</tr>
</tbody>
Each row has its own tr with those exact tds inside.
Some help would be appreciated :)
.click('//table[#id="admin-user-list"]/tbody/tr[./td[text()='test2']/td/button')
logic: //table[#id="admin-user-list"]/tbody/tr[./td[text()='test2']
- tr with td that has text
/td/button -button in that row
but actually this is not really good idea to do that, as you are searching for that value in each column. Better to use combination of columnName+value
Let's check on that table sample: https://www.w3schools.com/css/css_table.asp
We'll search for table data in column by name, for example table column = Country, data = UK
//*[#id='customers']//tr/td[count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1][text()='UK']
again, logic is simple:
general locator is:
//*[#id='customers']//tr/td - we are searching for table data
with parameters: [text()='UK'] and position = same, as in column name [count(column_position)]
How to get column position:
just get column with needed text:
//*[#id='customers']//th[text()='Country'] and count it's preceding siblings:
//*[#id='customers']//th[text()='Country']/preceding-sibling::* , also we should add +1 , as we need current element's position. and count that staff, so here is the result: [count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1]
so having column position we can get general locator:
tableId = customers; columnName= Country; dataText = UK;
//*[#id='tableId']//tr/td[count(//*[#id='tableId']//th[text()='columnName']/preceding-sibling::*)+1][text()='dataText']
And here is locator to get hole row by data+columnName
//*[#id='customers']//tr[./td[count(//*[#id='customers']//th[text()='Country']/preceding-sibling::*)+1][text()='UK']]
and basically you can search anything inside of it, for example just add in the end
/td/button - to get button from it

Only highlight row in table with corresponding value of ID

I have a html table 'TemplateData' populated dynamically from a db table...so for example could end up like:
ID Name Age
1 John 23
2 Mick 27
3 Mark 29
When the user clicks an image on screen it will post back the corresponding ID value. From here I want to change the background colour of the associating row.
So for example '2' has been posted back in 'fid'. so I have tried...
function highlightRowInTable(fid) {
var dtable = $("#TemplateData");
dtable.addClass("highlightedRow");
}
However this highlightes the outer cells of the table. I only want to highlight the corresponding row.
Iv been messing around with parents and siblings but cant find any working examples on line...any ideas?
It looks like your code is selecting the entire table, and then applying a class to it, though it is hard to say for sure. If you have an event listener attached to your table, you should be able to get the child element that was clicked on and toggle its class.
document
.getElementById('table')
.addEventListener('click', function(event){
// now event refers to the part of the dom that was clicked on
console.log(event)
});
Though I'm not sure without looking at your code. if you already have listeners set up, you might need to give every row an id based on fid, so that your function could specify the id to add class to.
function highlightRowInTable(fid) {
$(fid).addClass("highlightedRow");
}
when you create your table you can add an attribute to your <tr> to help select it later when an image is clicked.
#foreach (var row in table)
{
<tr data-uid="#row[id]">
<td></td>
</tr>
}
function highlightRowInTable(fid) {
var rows = $('tr').filter('[data-uid="' + fid + '"]');
rows.addClass("highlightedRow");
}

Simple jQuery handle processing

I have a simple HTML page where I will be having few rows, each row specifies a record in database, I have some input fields on each to collect and a link at the end, when I click that I need to collect the input field values on the same row.
The HTML goes like this:
<tr>
<td>Name</td>
<td><input name="mode_sort"/></td>
<td><input name="mode_selected" type="checkbox"/></td>
<td>Add</td>
</tr>
So I will be writing my code to collect input fields on the row when I click the "Add" link, I'm not sure how to pass the current clicked selector and get the field values with that in add_this_mode() function.
Within the function you can use jQuery traverse methods to isolate the parent row and then to find elements within that row
function add_this_mode( elem){
/* get parent row */
var $row = $(elem).closest('tr');
/* use find() to get other elements in row */
alert( $row.find('[name=mode_sort]').val() );
}

Delete table row script deleting static AND appended rows instead of appended/current

I have a script working on a single page with a + button to append a row to the table and in the append row is included a - button to remove THAT row only. THREE rows are static and the plus button allows the user to add more rows if need be..
When I try running it on a separate page (I've changed the function name and button/table names) in a nested table - after clicking the + to append a new row (which works fine), soon as I click the "-" button it removes ALL the rows including the static ones, not just the current row.
I've tried closest in the function, it was parents before - neither work.. should I specify table[1] or something like that?
Here is the delete function:
$("body").on("click", "input.deleteRow", function() {
$("#RfqTable").closest("tr").remove();
});
delete button:
input type="button" class="deleteRow" value="-" onclick = "deleteRow()"
table
table class="table table-bordered" id="RfqTable"
delete row button appended
input type="button" class="deleteRow" value="-" onclick = "deleteRow()"
Fixed: In the JS function i changed this:
$("#RfqTable").closest("tr").remove();
to this
$("#RfqTable tr:last").remove();
and now its working -

How to get table id using Jquery?

In my Java program I have a List<DemoTable>.
List<DemoTable> demotable = new ArrayList<DemoTable>();
DemoTable is a class with id,name,and details variables.
I display these details using Jquery..
<table>
<c:forEach items="${modalAttribute.demotable}" var="demo">
<tr class="M_row_bg M_read">
<td><input type="checkbox" id="isDelete"/></td>
<td><label for="name">${demo.name}</label></td>
<td><label for="totalExperience">${demo.details}</label></td>
</tr>
<c:forEach>
</table>
Data will be displayed correctly ... but when check box is clicked I want to get Table row id:
$("#isDelete").click(function(){
if (this.checked){
alert('checked');
alert(demo.id);
} else {
alert('unchecked');
}
} );
I expect this alert to give the DemoTable id, but this alert does not show. Also, this click only works for the first row of the table.
How can I get the DemoTable id when I click the check box?
What does my code need to work with each row of table click event, not just the first row?
you're using #isDelete multiple times in the table. This is illegal, and the reason your code only works on the first row. Use a class instead.
your table rows don't even have an ID. They do however have an implicit index.
you should give your table an ID
you can use "event delegation" and just register a single click handler on a common parent element (i.e. the table) which then uses event bubbling to figure out which actual element was clicked. This can be more efficient than registering the exact same event handler explicitly on every matching element.
Try this instead:
$('#myTable').on('click', '.isDelete', function(){
if (this.checked) {
var rowId = $(this).closest('tr').index(); // row within table (0 based)
}
});

Categories

Resources