how to remove row and add css class when button clicked - javascript

here is the fiddle
https://jsfiddle.net/shaswatatripathy/enq0kfqL/2/
how to write the remove function and how to add a css class to a row which is clicked .
1.when i click remove the clicked row should get removed
when i click the row - row should get highlightrow css class attached
also have to check if the table has any rows or not and put it in a var
at a time only one row should be in red (clicked row) if no row is selected the remove button should not be visible
HTML
col1header
col2header
CSS
.visibilityHide {
visibility: hidden;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
JS or Jquery
function add()
{var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
}
function getdetails(row)
{
$('#removerow').css('visibility', 'visible');
}

This is the updated javascript code. This will meet all your requirements.
function add()
{
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove()
{
$(".highlightRow").remove();
$('#removerow').addClass('visibilityHide');
$("#dropDown").prop("disabled", $("#myTableid tbody tr").length > 0);
}
function getdetails(row)
{
$('#removerow').toggleClass('visibilityHide', $("#myTableid tbody tr").length === 0);
$(".highlightRow").removeClass("highlightRow");
$(row).addClass("highlightRow");
}

Try this one. if it'll work
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
$('.removeClass').remove(); //remove clicked row
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
if($('table tbody tr').length===0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}
}
function getdetails(row){
$('#removerow').show();
$(row).addClass('removeClass'); //add class on clicked row
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
#removerow {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
Checking if the row is the last one is this part of the code
if($('table tbody tr').length==0) {
alert('This last child has been removed');
$("#dropDown").prop("disabled", false);
}

Do it like below (All solutions what you asked for):-
function add(){
var addRow1;
var addRow2;
addRow1 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow1" + "</td><td>" + "col2valuerow1" + "</td></tr>";
addRow2 = "<tr onclick="+"getdetails(this)"+"><td>" + "col1valuerow2" + "</td><td>" + "col2valuerow2" + "</td></tr>";
$("#myTableid tbody").append(addRow1);
$("#myTableid tbody").append(addRow2);
}
function remove(){
var index = parseInt($('.removeClass').index())+1;
$('.removeClass').remove(); //remove clicked row
$('.removed_row').html("<strong>row number "+index+ " removed</strong>");
if($('table tbody tr').length <=0){
$('#removerow').hide();
}
}
function getdetails(row){
$('#removerow').css('display', 'block');
$('.removeClass').removeClass('removeClass');
$(row).addClass('removeClass'); //add class on clicked row
}
.visibilityHide {
display: none;
}
.highlightRow{
color:red;
}
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
/* styling for added class so that it looks something different when class added */
.removeClass{
color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTableid">
<thead>
<th>
col1header
</th>
<th>
col2header
</th>
</thead>
<tbody>
</tbody>
</table>
<input type="button" id ="addrows" value="add" onclick="add()" />
<input type="button" id="removerow" value="remove" onclick="remove()" class="visibilityHide" />
<br>
<br>
<br>
<div class="removed_row"></div>

You can check the answer in my update:
function remove()
{
window.selectedRow.remove();
$('#removerow').css('visibility', 'hidden');
}
function getdetails(row)
{
removeHighlights();
window.selectedRow = row;
row.classList.add("highlightRow");
$('#removerow').css('visibility', 'visible');
}
function removeHighlights() {
var elements = document.getElementsByClassName("highlightRow");
while(elements.length > 0){
elements[0].classList.remove('highlightRow');
}
}
https://jsfiddle.net/g63zpuuz/

Related

Dynamically Built Jquery Table Assigning Row Data to Variables

I have a table built dynamically in my view, I populated a table with values from a jquery popup modal dialog. What i am trying to accomplish is getting each cell in the row and assigning it to variable, at which point I am going to post the data to the database via an ajax call
I am fairly new to JS and jnquery and following many examples, I cant seem to figure out to assign the cell values to the variable, I have included the code below.
Here is the html for the table
<div class="row">
<div class="col-md-12">
<table id="myTest" class="table table-responsive">
<thead>
<tr>
<th>Sku Number</th>
<th>Product Name</th>
<th style="width:300px">Description</th>
<th>Quantity</th>
<th>Border</th>
<th>Ink Color</th>
<th>Action</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
<div style="padding:10px 0; text-align: right; ">
<input id="submit" type="button" value="Save Order" class="btn btn-warning" style="padding: 10px 20px; margin-right: 15px;" />
</div>
</div>
Here is the JS for populating the table
function addItem() {
var remove = $('<input type="button" id="remove" value="remove" style="width:80px" class="btn btn-danger" />');
var td = $("<td></td>");
td.append(remove);
var valid = true;
allFields.removeClass("ui-state-error");
if (valid) {
$("#myTest tbody").append(
"<tr>" +
"<td>" + skuNumber.val() + "</td>" +
"<td>" + productName.val() + "</td>" +
"<td>" + description.val() + "</td>" +
"<td>" + quantity.val() + "</td>" +
"<td>" + border.val() + "</td>" +
"<td>" + inkColor.val() + "</td>" +
"</tr>");
dialog.dialog("close");
$("#myTest > tbody tr:last").append(td);
//console.log(td);
}
return valid;
}
And when you hit the submit button I want to create a list of objects that contains each row in the table, and this is where I am having problems.
$("#submit").click(function () {
var isAllValid = true;
var list = [];
$("#myTest tbody tr td")
.each(function(index, ele) {
var orderItem = {
SkuNumber: skuNumber.val(),
ProductName: productName.val(),
Description: description.val(),
Quantity: quantity.val(),
Border: border.val(),
InkColor: inkColor.val()
};
list.push(orderItem);
console.log(orderItem);
});

stop onclick javascript function from repeating my rows in table

I have a button -
<a onclick="function edit_row()"></a>
When I click the button it invokes the function edit_row and opens a new row in a table which I can edit.
The problem is that every time I click the button, it opens a new row. I want to stop that. I want it to just open one row which holds the row id.
Script code:
function edit_row(process_id, row_id, item_id, quantity, price, total) {
$(".edit_row").remove();
$(".add_row").remove();
var row = '<tr class="bg-success"> <
td > <?php echo $lang['e_edit_items'];?>: < /td> <
td > '+ item_id +' < /td>';
row += '<td><?php echo $lang['
quantity '];?></td>';
row += '<td><input type="text" class="form-control" id="quant1" value="' + quantity + '"></td><td><?php echo $lang['
The - price '];?></td>';
row += '<td><input type="text" id="price1" class="form-control" value="' + price + '"></td>';
row += '<td><a class="btn btn-success btn-block"onclick="save_edit(' + process_id + ',' + row_id + ',' + item_id + ',' + quantity + ',' + total + ')"><?php echo $lang['
Save_edit '];?></a></td></tr>';
$("#" + row_id).after(row);
return false;
}
You can remove click event handler of clickable element like this example.
$("#button1").click(function(){
$("table").append("<tr><td>New-1</td><td>New-2</td><td>New-3</td></tr>");
$(this).unbind("click");
});
table, tr, td {
border: 1px solid black;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Add row
<table>
<tr>
<td>Column-1</td>
<td>Column-2</td>
<td>Column-3</td>
</tr>
<tr>
<td>Column-1</td>
<td>Column-2</td>
<td>Column-3</td>
</tr>
</table>
But there is many way to do this work. For example you can add disabled attribute to clickable element, if it is button, You can add data-* attribute or class to element or use variable to do this. See example of other way in jsfiddle

Show/Hide Not Working When Fields Added Using .after () Function [duplicate]

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 6 years ago.
When I add fields using the jQuery .after() function, the show/hide functionality does not work on those fields.
Here's a JSFiddle that demonstrates the issue:
JSFiddle Demo
The show/hide functionality works on the first row, but does not work on any rows added after that one. I think the code being written after the page has been loaded might be the issue, but I'm not certain. If that's the case, is there a work around other than hard coding a certain amount of rows?
Here's the code I'm working with:
CSS:
#Table {
font-family:"Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse:collapse;
}
#Table td, #Table th {
font-size:1em;
border:1px solid #98bf21;
padding:3px 7px 2px 7px;
}
#Table th {
font-size:1.4em;
text-align:left;
padding-top:5px;
padding-bottom:4px;
background-color:#A7C942;
color:#fff;
}
#Table tr.alt td {
color:#000;
background-color:#EAF2D3;
}
HTML:
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />
jQuery:
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function () {
$('.cause_details').hide();
$('.report_cause').change(function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function () {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});
This:
$('.report_cause').change(function () {
Only applies to the .report_cause elements that existed when it was called. To handle new elements, you need a delegated handler:
$(document).on('change', '.report_cause', function(){
Additionally, if you want the new elements initially hidden, modify your output HTML accordingly:
'<p class=\"cause_details\" style=\"display:none\">'+
var count_2 = 5;
var table_count2 = 1;
$(document).ready(function() {
$('.cause_details').hide();
$(document).on('change', '.report_cause', function() {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});
$('#btnAdd').click(function() {
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>' + table_count2 + '</td>' +
'<td>' +
'<select name=\"report_cause' + count_2 + '\" id=\"report_cause' + count_2 + '\" class=\"report_cause\">' +
'<option value=\'default\'>-</option>' +
'<option value=\'other\'>Other, Not Listed</option>' +
'</select>' +
'<p class=\"cause_details\" style=\"display:none\">' +
'<input type=\"text\" name=\"cause_detail_info' + count_2 + '\" id=\"cause_detail_info' + count_2 + '\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />' +
'</p>' +
'</td></tr>');
});
});
#Table {
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
border-collapse: collapse;
}
#Table td,
#Table th {
font-size: 1em;
border: 1px solid #98bf21;
padding: 3px 7px 2px 7px;
}
#Table th {
font-size: 1.4em;
text-align: left;
padding-top: 5px;
padding-bottom: 4px;
background-color: #A7C942;
color: #fff;
}
#Table tr.alt td {
color: #000;
background-color: #EAF2D3;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table style="width: 70%" id="Table" name="Table">
<tr>
<th>#</th>
<th>Cause</th>
</tr>
<tr>
<td>1</td>
<td>
<select name='report_cause2' id='report_cause2' class="report_cause">
<option value='default'>-</option>
<option value='other'>Other, Not Listed</option>
</select>
<p class="cause_details">
<input type="text" name="cause_detail_info" id="cause_detail_info" placeholder="Type cause here" size="48" maxlength="50" class="textbox required" value="" />
</p>
</td>
</tr>
</table>
<input type="button" id="btnAdd" name="btnAdd" value="Add More" class="button" />
Try this. The problem is that when you create a dynamic element, you need to again register change event on $('.report_cause').
$(document).ready(function(){
$('.cause_details').hide();
BindChange();
$('#btnAdd').click(function(){
count_2 = count_2 + 2;
table_count2 = table_count2 + 1;
$('#Table tr:last').after('<tr><td>'+table_count2+'</td>'+
'<td>'+
'<select name=\"report_cause'+count_2+'\" id=\"report_cause'+count_2+'\" class=\"report_cause\">'+
'<option value=\'default\'>-</option>'+
'<option value=\'other\'>Other, Not Listed</option>'+
'</select>'+
'<p class=\"cause_details\">'+
'<input type=\"text\" name=\"cause_detail_info'+count_2+'\" id=\"cause_detail_info'+count_2+'\" placeholder=\"Type cause here\" size=\"48\" maxlength=\"50\" class=\"textbox required\" value=\"\" />'+
'</p>'+
'</td></tr>');
BindChange();
});
});
function BindChange()
{
$('.report_cause').bind("change",function(){
if ($(this).val() == 'other'){
$(this).parent().find('.cause_details').show();
}else{
$(this).parent().find('.cause_details').hide();
}
});
}
https://jsfiddle.net/hnj6ed1y/12/
When you create the elements dynamically, you need to use event delegation to handle the events on them, so based on your jQuery version use .bind or .on API.
Just change in your code to:
$(document).on('change', '.report_cause', function () {
if ($(this).val() == 'other') {
$(this).parent().find('.cause_details').show();
} else {
$(this).parent().find('.cause_details').hide();
}
});

tr:nth-child css zebra striping after xml jquery parsing

How do I apply styling to a table after parsing XML data into the table?
In the code below I Created the first three rows of a table using html, then the additional rows were created by parsing XML. however the Zebra stripe styling was not applied to the table after the jquery call. I've tried my best to find the problem with my code but I'm stumped.
Here's a code sample of my html:
<head>
<title>Football Players</title>
<style>
table{
border-collapse: collapse;
border: solid 1px #dddddd;
width: 500px;
}
th{
text-align: left;
}
</style>
</head>
<body>
<table>
<tbody>
<tr>
<th>Name</th>
<th>Club</th>
<th>Number</th>
<th>Country</th>
</tr>
<tr>
<td>Lionel Messi</td>
<td>Barcelona</td>
<td>10</td>
<td>Argentina</td>
</tr>
<tr>
<td>Juan Mata</td>
<td>Manchester United</td>
<td>8</td>
<td>Spain</td>
</tr>
</tbody>
</table>
</body>
And the following is a snippet of my JQuery:
$(document).ready(function () {
$.ajax({
type: "GET",
url: "football_player.xml",
dataType: "xml",
success: processXML
});
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'>");
$("table tbody").append("<td>" + $(this).find("name").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("club").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("number").text() + "</td>");
$("table tbody").append("<td>" + $(this).find("country").text() + "</td>");
$("table tbody").append("</tr>");
});//close processXML
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}
});//close document.ready()
And lastly the XML file:
<football_players>
<football_player>
<name>Cristiano Ronaldo</name>
<club>Real Madrid</club>
<number>7</number>
<country>Portugal </country>
</football_player>
<football_player>
<name>Fernando Torres </name>
<club>Chelsea </club>
<number>9</number>
<country>Spain</country>
</football_player>
<football_player>
<name>Iker Casillas</name>
<club>Real Madrid </club>
<number>1</number>
<country>Spain</country>
</football_player>
<football_player>
<name>David Beckham</name>
<club>Los Angeles Galaxy</club>
<number>23</number>
<country>England</country>
</football_player>
</football_players>
Checking the console is always a good idea,The problem in your code probably is in the function processXML(xml).This is beacause your <tr> were closed before adding <td>.Hence it was not applying the color.
Change it to..
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'>"+"<td>" +
$(this).find("name").text() + "</td>"+"<td>" + $(this).find("club").text() + "</td>"+"<td>" + $(this).find("number").text() + "</td>"+"<td>" + $(this).find("country").text() + "</td>"+"</tr>");
});//close processXML
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}
Thanks to Varun I came up with the following which worked:
function processXML(xml) {
$(xml).find("football_player").each(function () {
$("table tbody").append("<tr class = 'myClass'><td>" + $(this).find("name").text() + "</td><td>" + $(this).find("club").text() + "</td><td>" + $(this).find("number").text() + "</td><td>" + $(this).find("country").text() + "</td></tr>");
});
$("table tbody tr:nth-child(odd)").css("background-color", "#dddddd");
}

Convert an particular TD element of a table to Select with pre-populated Options

I am very new to jQuery,so bear with me if it seems to be silly question.
I have an table with many TD's in each row.I need to convert an TD element with plain text belonging to a particular column into an TD with Select element with pre-populated options,when user clicks that TD of that column using jQuery.
You can't convert the td into a select, because that would result in an invalid document. What you can do, is put the select within the td. E.g.:
$('selector for the td in question').html(
'<select>' +
'<option value="1">One</option>' +
'<option value="2">Two</option>' +
'<option value="3">Three</option>' +
'</select>'
);
Here's a complete example, also demonstrating event delegation: Live Copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<meta charset=utf-8 />
<title>Select in Cell</title>
<style>
.type {
cursor: pointer;
white-space: nowrap;
}
table {
border: 1px solid #aaa;
border-collapse: collapse;
}
td, th {
border: 1px solid #aaa;
padding: 2px;
}
</style>
</head>
<body>
<p>Click cells in the type column.</p>
<table id="theTable">
<thead>
<tr>
<th>Type</th>
<th>Description</th>
</tr>
</thead>
<tbody>
<tr>
<td class="type">Thingy</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Widget</td>
<td>Blah</td>
</tr>
<tr>
<td class="type">Whatsit</td>
<td>Blah</td>
</tr>
</tbody>
</table>
<script>
(function() {
$("#theTable").on("click", ".type", function() {
var $this = $(this),
current = $this.text(),
select;
if ($this.find("select").length) {
return;
}
select = $(
'<select>' +
'<option>Thingy</option>' +
'<option>Widget</option>' +
'<option>Whatsit</option>' +
'</select>'
);
$this.html(select);
select.val(current).focus();
});
$("#theTable").on("blur", ".type select", function() {
var $this = $(this);
$this.closest('td').text($this.val());
});
})();
</script>
</body>
</html>
Interesting task. Try this solution:
$('table').on('click', 'td', function(e) {
if ($(this).data('converted')) {
e.stopPropagation();
return;
}
$(this).data('converted', $(this).text());
var rowIndex = this.parentNode.rowIndex,
index = this.cellIndex + 1,
options = $(e.delegateTarget).find('td:nth-child(' + index +')').map(function(i) {
var text = $(this).data('converted') || $(this).text();
return '<option ' + (rowIndex == i ? 'selected' : '') + '>' + text + '</option>';
}).get();
$(this).html('<select>' + options.join('') + '</select>');
});
Demo: http://jsfiddle.net/As9dY/2/
Q: How to add a select dropdown to a TD dynamically?
Here's how you do it:
HTML:
<table>
<tr><th>Column A</th><th>Column B</th></tr>
<tr><td>1</td><td>6</td></tr>
<tr><td>2</td><td>7</td></tr>
<tr><td>3</td><td>8</td></tr>
<tr><td>4</td><td id="nine">9</td></tr>
<tr><td>5</td><td>10</td></tr>
</table>
jQuery:
$(document).ready(function() {
var isAppended = false;
var select = "<select name='mySelect'>" +
"<option value='volvo'>Volvo</option>" +
"<option value='saab'>Saab</option>" +
"<option value='opel'>Opel</option>" +
"<option value='audi'>Audi</option>" +
"</select>";
$("#nine").click(function() {
if (!isAppended) {
$(this).append(select);
isAppended = true;
}
});
});
JSFIDDLE DEMO

Categories

Resources