Remove a row on uncheck - javascript

I have a table(1) with checkbox against each row. When i click a checkbox its value is shown in another table(2). In table(2) each row has a remove option. If i click remove, the row will be removed. In the same way if i uncheck the checkbox in table(1), the corresponding row in table(2) should be removed.So how should i remove a row on uncheck.I have placed this part of code in else block.
$(document).ready(function(){
$('.isSelected').click(function() {
var pdtname = $(this).attr('data-productname');
if ( $('.isSelected:checked').length > 0) {
$("#result").show();
var table = $('<table></table>').addClass('tfoo');
var row = $('<tr></tr>').addClass('rfoo').text(pdtname);
var link = $('<a href="javascript:void(0);">/a>').addClass('lfoo').text('Remove');
row.append(link);
table.append(row);
$('#result').append(table);
$("#result").on('click','.lfoo',function(){
$(this).parent().parent().remove();
});
} else {
$('.isSelected[data-productname="pdtname"]').on('click','.lfoo',function(){
$(this).parent().parent().remove();
});
}
});
});
HTML
<div id="result" ></div>
<td><form method='post' action='<c:url value="compareproducts.html"/>' >
<input class="isSelected" type="checkbox" name='id' value='${product.id}'
data-productname="${product.productName}" >
</form>

As per our conversation in the chat. A quick solution would be to add a data-productname to the table so when you uncheck a checkbox, it removes the table with the same data-productname (notice that for this to work, the productname must be unique).
You can see an example on this jsfiddle: http://jsfiddle.net/4g8nL9t5/1/

Related

javascript insert new row same as first row when press enter in html table last row

I want to insert new row in html table when user press enter on keyboard. At beginning I already added first tr when create the table. In this tr, first td contain html dropdown list($select_chooseitem) that contain data from database.Second column is textbox. I want to use javascript to get first tr element set and create new row based on that. tr element set would be like:
<tr>
<td>first col</td>
<td>second col</td>
</tr>
I do not want to declare new tr element set. But, want to retrieve first tr element set from table. Is this possible?
$row_html ='<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>';
$html_complete='<!DOCTYPE html>
<html lang="en">
<head>
<script>
$(function () {
// Change the selector if needed
var $table = $(".mt-table-edit");
//addNewRow();
function addNewRow() {
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td><input/></td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13) {
addNewRow();
}
});
// add template after the last row
$table.find("tbody:last-child").append($tr);
// focus on firt input of newly added row
$tr.find("td:first input").focus();
}
});
</script>
</head>
<body>
<table class="mt-table-edit">
'.$row_html.'
</table>
</body>
</html>';
echo $html_complete;
//echo $query_tbltemplateitems;
Since first one not work, other method I tried was getting $select_chooseitem in javascript to create tr element set. I tried access php variable($select_chooseitem) in js by addNewRow('.$select_chooseitem.'); ,but not working. How is proper way to access php variable value from js?
<script>
$(function () {
var $table = $(".mt-table-edit");
var $row = $(".mt-table-edit").children("tr:first");
addNewRow('.$select_chooseitem.');
function addNewRow(var)
{
//get row template. We must use html() for new instance other event handler will get attached to last row
//var $tr = $("<tr><td><input/></td><td><input/></td><td><input/></td><td><input/></td></tr>");
var $tr = $("<tr><td>var</td><td><input/></td></tr>");
$tr.find("td").eq($tr.find("td").length - 1).keyup(function (e) {
if (event.keyCode === 13)
{
addNewRow(var);
}
});
$table.find("tbody:last-child").append($tr);
$tr.find("td:first input").focus();
}
});
</script>
I have tried declare variable in js and try to access in js in head of html. not successful too.
Example:
<?php
$select_chooseitem='<select>'.$option_list.'</select>';
?>
<script>
var select_chooseitem=<?php echo $select_chooseitem;?>;
</script>
Thanks in advance.
Kindly try the code snippet below.
$(document).on( 'keyup', '.name', function(){
if (event.which == 13 && $(this).closest("tr").is(":last-child")) {
var $tblbody = $('#mytable').find("tbody"),
$tbltrlast = $tblbody.find("tr:last"),
$trnew = $tbltrlast.clone();
$tbltrlast.after($trnew);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id='mytable'>
<tbody>
<tr>
<td><input type='text' name='name' class='name' value='John Doe'></td>
</tr>
</tbody>
</table>
If you want to access the first child of tr you can use this:
$('table tr:first-child')
Since you are using jQuery this code might be useful.
This code searches for a table tag then selects the first tr tag
$('table tr:first-child')
You can also achieve this using plain css
table tr:first-child{
color: red;
}
The required markup for the row is constructed.
markup = "<tr>
<td>'.$select_chooseitem.'</td>
<td><input type="text" name="order"></td>
</tr>"
The table body is selected to which the table rows to be added.
tableBody = $("table tbody")
Finally the markup is added to the table body.
tableBody.append(markup)
the solution Kaptian delivered seams like a good one, but he copys the last row of the Table. if you set newrow like that, it should do the job.
var newrow = $('#mytable tr:first-child').html();
Thank you for suggestion and answers. By using .clone().appendTo() and keyup(function(e), I'm able to add new row by enter on keyboard. Every time enter, it did add new row after last tr. But ,could not limit add row will execute only when enter in last td of last row.
$(function() {
// Change the selector if needed
var $table = $(".mt-table-edit");
//var $row = $(".mt-table-edit").children("tr:first");
addNewRow();
function addNewRow() {
var $tr = $table.find("tr:eq(0)").clone();
//$(".mt-table-edit").keyup(function(e) {
//$(".mt-table-edit tr:last td:last").keyup(function(e) {
$($table.find("tbody:last-child")).keyup(function(e) {
if (event.keyCode === 13) //test enter key press on keyboard
{
//$table.find("tbody:last-child").append($tr);
$table.find("tr:eq(0)").clone().appendTo($table.find("tbody:last-child"));
}
});
$tr.find("td:first input").focus();
}
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<html lang="en">
<body>
<table class="mt-table-edit" border="1">
<tr>
<td>first col</td>
<td><input type="text" name="order"></td>
</tr>
</table>
</body>
</html>
jsfiddle
Thanks in advance.

Remove dynamic columns added to HTML table with this.closest

I have an HTML table I am adding columns to dynamically. Each input column added also has a check mark to continue adding it and an x mark to remove it. The remove function is not working as I am trying to remove the closest td but then all of the added input columns are removed when I click on the x mark. How do I make it so just the selected dynamic column is removed? Here is what I have
var myform = $('#myform'),
iter = 0;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
if(trow.index() === 0){
trow.append('<td><input type="text" id="input"><input type="image" src="checkmark.png" name="accept" class="accept" id="accept" /><input type="image" src="xmark.png" name="cancel" class="cancel" id="cancel" /></td>');
}
});
iter += 1;
});
$('#cancel').click(function () {
$(this).closest("td").find('.input').remove();
});
Based on your code you seem to be appending a cell(TD element) to a table row(TR) of the table.
To remove the cell (or any element within that cell) you can pass the element(this) that was clicked to a function like this:
<input type="button" value="cancel" id="cancel" onClick="removeCell(this)" />
and then define a new function that will remove the parent element(the TD element in this case) or a different element within the cell like this:
function removeCell(clickedElement) {
// select the parent element(td element) of the cancel button, and remove it
$(clickedElement.parentElement).remove();
}
Demo

Child Div is not removed when tried to remove using Jquery

Clearing child div inside parent div, there are many answers like :
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
Probably I have listed all possible way to remove the div's, but even after using all these, I still not able to clear all the div's inside Parent Div. let me explain what I am doing and what I need.
Scenario :
I have two container-1, one of the container has input search box, where I can search for entering employee name and select few employees Ex. 5 and can use "Add" button to move those employees to the other container-2 which is 'div'.
Now I click on report button event and get the information of those 5 people in different aspx, now if i go back to the page where i have to search for another 3 employees and when I again click on the "Add" button, it should add only 3 employees instead it is adding last searched 5 + 3 employees!!.
So i am trying to clear the 5 employees inside that div after i click on "Report" button , when i use alert() it says it has 0 element, but when I add it for the second time, it appends the data again, which i dont need. here is the code :
Points to remember :
1. ParentDiv is the container-2
2. ChildDiv is the child div inside ParentDiv(which is dynamically appended when we select 5 employees on "Add" button click"
Here is the code:
HTML :
<table id="topTable">
<tr>
<td id="leftpane">
<h4>Search for Employee by Name or Profile:</h4>
<input type="text" id="EmployeeSearchBox" class="search-box" aria-multiselectable="true" />
<select id="EmployeeList" size="20" multiple></select>
</td>
<td id="centerpane">
<div> <input type="button" value="Add >>" class="AddButton" id="buttonAdd" /></div>
<div> <input type="button" value="Add All >>" class="AddButton" id="buttonAddAll" /></div>
</td>
<td id="rightpane">
<h4>Selected Employees:</h4>
<div id="ParentDiv"></div>
</td>
</tr>
</table>
Run Report button event
<input class="data" type="submit" name="cmdSubmit" value="Run Report" onclick="return FormValidate();"
onserverclick="RunReport" runat="server" id="Submit1" />
Add Button Click :
which moves the employees from container-1 to container-2.
$(document).on('click', '#buttonAdd', function (e) {
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
var myNode = $("#ParentDiv")[0];
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
On click of "Report" button it should clear all the elements from ParentDiv/ChildDiv which is what I did, but still it is not clearing it, how can I resolve/remove these elements once "Report" button event clicked.
Here is a sample of "Report" button event :
function FormValidate() {//Part of my other code
$(".ChildDiv").html("");
$('.ChildDiv > div').remove();
$(".ChildDiv").html("");
$("#ParentDiv").html("");
$(".ChildDiv div").remove();
$(".ChildDiv div").empty();
$('.ChildDiv ').find('div').remove();
}
None of them is working, i feel there is an issue with the "Add" button event, where it is storing the data.
NOTE :
I don't want to clear the array of employee list, since I want to select multiple employees again again Ex. I can select 2 employees starts with the letter "M" and I can search the 2 employees of letter "L" and add those 2 employees, the container should hold 4 employees before "Report" button click.
Let me know if I am clear enough.
Console Log
Finally I could able to fix the issue, i was facing, I am posting the answer, now it is working as I need.
$(document).on('click', '#buttonAdd', function (e) {
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = []; // Clearing the hash, so that it can add fresh employees, if count == 0 in container- 2.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
else { // If there are existing employees in container-2 then append few more.
$('#EmployeeList :selected').each(function (i, selected) {
myHash[$(selected).val()] = $(selected).text();
});
}
var myNode = $("#ParentDiv")[0];
console.log(myNode);
while (myNode.firstChild) {
myNode.removeChild(myNode.firstChild);
}
for (var emp_id in myHash) {
var emp = $("#ParentDiv").append("<div class= ChildDiv id=" + emp_id + ">" + myHash[emp_id] + " <span class='close'>×</Span> </div>");
}
$('#EmployeeSearchBox').val("").trigger('input');
});
What I did
Since I should be able to append multiple employees by searching, that is handled in 'else' part, if I generated the "Report" then, I am clearing the Container-2.
When I come back to page to search few more employees, by this time Container-2 will not be having any employees, so
var div_count = $('#ParentDiv').find('div').length;
if (div_count === 0) {
myHash = [];
//....
}
will clear the array which allow me to add fresh employees, hence it solved my problem :)
Thanks all for the support.
Edited to adjust on comments:
You need to clear the myHash variable. Otherwise employees will be added again from there.

alert something whenever a checkbox is selected or checked

I've tried making a function that is triggered by whenever a checkbox inside a table is checked but that didn't work well. I've tried making a function located in a $(document).ready but it didn't also work.
this is my html code
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
this is my function
$(document.ready)(function () {
$("#row input:checked'").each(function(){
$('#select').click(function(){
alert('clicked');
});
});
My main goal is counting the selected checkboxes and not allowing the user to check more than 3. But for now I'm trying to make a function that would recognize whenever a checkbox is selected
});
Your DOM ready should be $(document).ready(function(){...
You shouldn't bind click to each checkbox by iterating through only checked ones
Bind using event delegation, and then check the state on click.
As per your question, your problem is to disallow user to check more than three checkboxes.
You could do that by doing a length of all checked inputs, and then overriding new checks if the length exceeds three:
Demo: http://jsfiddle.net/abhitalks/uERSd/1/
// bind click to all input of type checkbox inside #row via delegation
$("#row").on("click", "input[type='checkbox']", function() {
// check the length i.e. total number of inputs which are currently checked
var tot = $("#row input[type='checkbox']:checked").length;
if (tot > 3) {
// disallow new checks if three are already checked
this.checked = false;
}
});
To recognize whenever checkbox is selected, you can use:
$("#select").change(function() {
if(this.checked) {
alert('clicked');
}});
Try this : Here document.ready syntax is corrected and jquery modified to get total count of checked checkboxes inside td with id='row'
$(document).ready(function(){
$("#row input[type='checkbox']").click(function(){
var count = $("#row input[type='checkbox']:checked").length;
alert("total checked checkbox is : "+count);
});
});
This code will work
$(document).ready(function() {
$("#select").change(function() {
if(this.checked) {
alert('checked');
}});
});
Your HTML
<table class="tableTable">
<tr id="tableTr">
<td id='row'><input type='checkbox' name='helloname' value="helloval" id='select'> hello </td>
<td id='row1'><input type='checkbox' name='helloname' value="helloval" id='select1'> hello1 </td>
<td id='row2'><input type='checkbox' name='helloname' value="helloval" id='select2'> hello2 </td>
<td id='row3'><input type='checkbox' name='helloname' value="helloval" id='select3'> hello3</td>
</tr>
</table>
JQUERY
$(document).ready(function(){
$("#tableTr").on("click", "input[type='checkbox']", function() {
var count = $("#tableTr input[type='checkbox']:checked").length;
if (count > 3) {
this.checked = false;
alert("only 3 items can be checked");
}
});
});

getting values of the clicked row and assigning cell's values to corresponding inputs

I have a table with id="selector".
Each row's cell has a corresponding input to it.
<td class="cell1"><b>Cell 1</b></td>
<input type="text" name="cell1" id="cell1">
What I need to do is to capture the whole row and assign certain cells to the inputs (not all cells will be assigned to inputs). In this example it would just be cell1.
<script type="text/javascript ">
$('#selector tr').click(function() {
var values = ($(this).html()); // this is the whole row
// no idea what to do now
$("#cell1").val($(this)) // don't know how to select cell1
});
</script>
EDIT: #sub1 -> #cell1
There is no need to "capture the whole row" via html().
$('#selector tr').click(function() {
$("#sub1").val( $(this).find("td").get(0).text() );
});

Categories