I am attempting to give each row that is dynamically added a unique ID. Basically by adding to the number each time the user clicks the add button. It is adding an ID, but not correctly, it is showing up as "undefined" in the dev tools.
var counter = 0;
function appendRow(id, style) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length, 'id'); // append table row
row.setAttribute('id', style);
row.setAttribute('idName', style);
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cust' + counter);
counter++
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
}
td {
width: 100px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>Somewhere</td>
</tr>
</table>
</div>
The reason why the new elements are showing up as "undefined" is because the style argument of appendRow has not been provided.
To get the functionality that you're going for you have to remove style from the appendRow arguments and replace the references to style inside appendRow with 'cust' + counter.
Your style value is null here please check style value I have also added fiddle
Please check this code, When user is clicking on button the style value is undefined.
<button id="addCust" class="addSort" ***onclick="appendRow('custList')"***>add customer</button>
Appendrow function requires two parameters and you are just passing one.
var counter = 0;
$('#addCust').click(function() {
var table = document.getElementById('custListTop'); // table reference
length = table.length,
row = table.insertRow(table.rows.length, 'id'); // append table row
row.setAttribute('id', counter);
row.setAttribute('idName', counter);
var i;
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cust' + counter);
counter++
}
});
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
}
td {
width: 100px;
}
tr:nth-child(even) {
background-color: #fff;
}
tr:nth-child(odd) {
background-color: #eee;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="addCust" class="addSort">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>Somewhere</td>
</tr>
</table>
</div>
Related
I am working on a project where I have an HTML table and I need to offer users the option to swap two HTML table cells content.
Specifically, a user can click to select a row, then choose to move that row up or down. Really, they are only moving the content of column 2, which represents the information. Column 1 represents order, which will not change.
The table will be two total columns.
Column 1 will represent linear order (i.e. 1-10), it will not change.
Column 2 will be database-provided information (in the example code I provided last name).
I have built two buttons, up and down, and utilized two Javascript functions that allow a user to select a row and move it up or down.
The current code successfully moves a whole row to go up or down, but I only need the cell contents of column 2 to go up or down.
Please take a look at the provided code and JSFiddle and let me know how I can solve this? Thanks in advance!
var index; // variable to set the selected row index
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
// clear the selected from the previous selected row
// the first time index is undefined
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if (direction === "up") {
if (index > 1) {
parent.insertBefore(rows[index], rows[index - 1]);
// when the rowgo up the index will be equal to index - 1
index--;
}
}
if (direction === "down") {
if (index < rows.length - 1) {
parent.insertBefore(rows[index + 1], rows[index]);
// when the row go down the index will be equal to index + 1
index++;
}
}
}
tr {
cursor: pointer
}
.selected {
background-color: red;
color: #fff;
font-weight: bold
}
button {
margin-top: 10px;
background-color: #eee;
border: 2px solid #00F;
color: #17bb1c;
font-weight: bold;
font-size: 25px;
cursor: pointer
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta content="width=device-width, initial-scale=1, shrink-to-fit=no" name="viewport">
<meta content="30" http-equiv="refresh">
<title> {{.Title}} </title>
<style>
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
</style>
</head>
<body>
<header>
</header>
<main>
<table id="table" border="1">
<tr>
<th>Order</th>
<th>Last Name</th>
</tr>
<tr>
<td>1</td>
<td>Smith</td>
</tr>
<tr>
<td>2</td>
<td>Johnson</td>
</tr>
<tr>
<td>3</td>
<td>Roberts</td>
</tr>
<tr>
<td>4</td>
<td>Davis</td>
</tr>
<tr>
<td>5</td>
<td>Doe</td>
</tr>
</table>
<button onclick="upNdown('up');">↑</button>
<button onclick="upNdown('down');">↓</button>
</main>
<!-- Bootstrap core JavaScript -->
<script src="/vendor/jquery/jquery.min.js"></script>
<script src="/vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
<script src="/js/sidebar.js"></script>
</body>
</html>
Link to JSFiddle
This answer makes changes the posted code for simplicity (at least on the surface) and to prevent moving the header row down the table using the buttons:
A reference to the selected row is held rather than an index.
In HTML, the header row has been placed within a thead element, and the data rows within a tbody element (important in code).
When moving a row, the order of two rows is reversed, and then the textContent of their first cells swapped - without moving the "order" column cells to different rows. If this is too simple you could swap the innerHTML property of the cells instead.
Whilst making changes, clicking a row a second time was used to deselect it: clicking outside the table would be another thing you could monitor, as you wish.
"use strict";
const tbody = document.querySelector("#table tbody");
let selected = null;
tbody.addEventListener("click", function(e){
let row = e.target.closest("tr");
if( row === selected) {
row.classList.toggle("selected")
selected = null;
}
else {
if(selected) {
selected.classList.toggle("selected");
}
selected = row;
row.classList.toggle("selected");
}
});
function upNdown( direction) {
let up, down;
if( selected) {
up = direction == "up" ? selected : selected.nextElementSibling;
down = direction == "up" ? selected.previousElementSibling : selected;
if( up && down) {
tbody.insertBefore(up, down); // put up before down
var temp = up.firstElementChild.textContent; // swap first cells' text content
up.firstElementChild.textContent = down.firstElementChild.textContent;
down.firstElementChild.textContent = temp;
}
}
}
tr {
cursor: pointer
}
.selected {
background-color: red;
color: #fff;
font-weight: bold
}
<table id="table" border="1">
<thead>
<tr>
<th>Order</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Smith</td>
</tr>
<tr>
<td>2</td>
<td>Johnson</td>
</tr>
<tr>
<td>3</td>
<td>Roberts</td>
</tr>
<tr>
<td>4</td>
<td>Davis</td>
</tr>
<tr>
<td>5</td>
<td>Doe</td>
</tr>
</tbody>
</table>
<button onclick="upNdown('up');">↑</button>
<button onclick="upNdown('down');">↓</button>
It depends on exactly what you want. You mention having tried moving innerHTML so this snippet does that - leaving any attributes on the two tds unmoved (see Note below):
var index; // variable to set the selected row index
function getSelectedRow() {
var table = document.getElementById("table");
for (var i = 1; i < table.rows.length; i++) {
table.rows[i].onclick = function() {
// clear the selected from the previous selected row
// the first time index is undefined
if (typeof index !== "undefined") {
table.rows[index].classList.toggle("selected");
}
index = this.rowIndex;
this.classList.toggle("selected");
};
}
}
getSelectedRow();
function upNdown(direction) {
var rows = document.getElementById("table").rows,
parent = rows[index].parentNode;
if (direction === "up") {
if (index > 1) {
// get the relevant cell which is the second one as we know only tds are the children
let td = rows[index].children[1];
let tdAbove = rows[index - 1].children[1];
let temp = td.innerHTML;
td.innerHTML = tdAbove.innerHTML;
tdAbove.innerHTML = temp;
// when the rowgo up the index will be equal to index - 1
index--;
}
}
if (direction === "down") {
if (index < rows.length - 1) {
let td = rows[index].children[1];
let tdBelow = rows[index + 1].children[1];
let temp = td.innerHTML;
td.innerHTML = tdBelow.innerHTML;
tdBelow.innerHTML = temp;
// when the row go down the index will be equal to index + 1
index++;
}
}
}
.bd-placeholder-img {
font-size: 1.125rem;
text-anchor: middle;
-webkit-user-select: none;
-moz-user-select: none;
user-select: none;
}
#media (min-width: 768px) {
.bd-placeholder-img-lg {
font-size: 3.5rem;
}
}
tr {
cursor: pointer
}
.selected {
background-color: red;
color: #fff;
font-weight: bold
}
button {
margin-top: 10px;
background-color: #eee;
border: 2px solid #00F;
color: #17bb1c;
font-weight: bold;
font-size: 25px;
cursor: pointer
}
<body>
<header>
</header>
<main>
<table id="table" border="1">
<tr>
<th>Order</th>
<th>Last Name</th>
</tr>
<tr>
<td>1</td>
<td>Smith</td>
</tr>
<tr>
<td>2</td>
<td>Johnson</td>
</tr>
<tr>
<td>3</td>
<td>Roberts</td>
</tr>
<tr>
<td>4</td>
<td>Davis</td>
</tr>
<tr>
<td>5</td>
<td>Doe</td>
</tr>
</table>
<button onclick="upNdown('up');">↑</button>
<button onclick="upNdown('down');">↓</button>
</main>
Note: in the question the idea of moving a whole element, not just its contents, is introduced. You could do that instead of swapping the contents (i.e. all the attributes would also get moved) by using for example outerHTML. However, this may not be what you want because there may be for example an inline style on the top element which highlights it in gold if this is a leader board. It depends on exactly what your requirement is.
Note also that the snippet assumes the table is well-formed in the sense that there are no non-td elements as direct children within the selectable rows.
I'm new to Javascript and learn about querySelector(), createElement(), setAttribute and loop.
I try to create a table with a row, which contains 5 cells in it.
Imagine I create in HTML file. I use following code to execute my idea:
// 1. select id = pixelCanvas and store in var table.
const table = document.querySelector('#pixelCanvas');
// 2. create table row element <tr></tr> and append to var table.
table.appendChild(document.createElement('tr'));
// 3. create element table data and store in var data.
const data = document.createElement('td');
// 4. set html attribute with class="cell", width: 20px & height: 20px for table data
data.setAttribute('style', 'width: 20px; height: 20px:');
// 5. use for loop and appendChild() to append 5 <td></td> to <tr></tr>
for (i = 0; i < 5; i++) {
let tblRow = document.querySelector('tr');
tblRow.appendChild(data);
};
Here is the result in HTML page.
Obviously my idea doesn't work as expected. Appreciate your advice: where goes wrong?
prefer to use css to style attributes.
there is also js methods for tables :
HTMLTableElement.insertRow()
HTMLTableRowElement.insertCell()
const myTable = document.querySelector('table#pixelCanvas')
for (let r=0;r<5;++r) {
let row = myTable.insertRow()
for (c=0;c<5;++c) {
row.insertCell().textContent = `${r}.${c}`
}
}
table#pixelCanvas {
border-collapse: collapse;
font-size: 9px;
}
table#pixelCanvas td {
padding: 5px;
width: 20px;
height: 20px;
border: 1px solid black;
}
<table id="pixelCanvas"></table>
Your code is very close to working - you just need to create a seperate td element for each iteration of the for loop, and setting the style attribute is much easier when done via the .style property of the element.
Also instead of trying to query for the row you have just created, you can use the return value of the createElement function - it will give you the variable containing the new element.
See this snippet:
const table = document.querySelector('#pixelCanvas');
const colors = ["red", "orange", "green", "blue", "purple"];
const row = document.createElement('tr');
table.appendChild(row);
for (i = 0; i < 5; i++) {
const cell = document.createElement('td');
cell.style.width = "20px";
cell.style.height = "20px";
cell.style.backgroundColor = colors[i];
row.appendChild(cell);
};
<table id="pixelCanvas"></table>
You mean this
Move the row outside the loop and if you need the cells to be the same, clone the one you made - you also had a typo in it (colon instead of semicolon)
I would also target the tbody since a table should have such a thing
const table = document.querySelector('#pixelCanvas tbody');
const data = document.createElement('td');
data.setAttribute('style', 'width: 20px; height: 20px;');
let tblRow = document.createElement('tr');
for (let i = 0; i < 5; i++) {
let cell = data.cloneNode(true)
cell.textContent = i;
tblRow.appendChild(cell);
}
table.appendChild(tblRow);
<table id="pixelCanvas">
<thead>
</thead>
<tbody>
</tbody>
</table>
Result
<table id="pixelCanvas">
<thead>
</thead>
<tbody>
<tr>
<td style="width: 20px; height: 20px;">0</td>
<td style="width: 20px; height: 20px;">1</td>
<td style="width: 20px; height: 20px;">2</td>
<td style="width: 20px; height: 20px;">3</td>
<td style="width: 20px; height: 20px;">4</td>
</tr>
</tbody>
</table>
I am trying to add a table row containing a div dynamically using JavaScript. Everything is working fine except, when it is added, my columns move slightly. Weirdly, it seems to only happen when the div contains text longer than a certain length.
In the stripped down version below, you can see the problem clearly. After trying it, go to line 24 of the JavaScript, remove the "i" at the end of the string, and it will no longer move my columns.
JSFiddle
setEventListeners();
function setEventListeners() {
var hideMe = document.getElementById('hide-me');
var table = document.getElementById('table');
hideMe.addEventListener('mouseenter', showHoverMenu);
table.addEventListener('mouseleave', deleteOtherMenus);
}
function showHoverMenu(e) {
e.preventDefault();
deleteOtherMenus();
var tr = document.createElement('tr');
tr.setAttribute('class', 'row-menu-parent')
var td = document.createElement('td');
td.colSpan = 4;
var rowMenu = document.createElement('div');
rowMenu.classList.add('row-menu');
var div = document.createElement('div');
// Delete the "i" at the end of the string and try hovering again
div.innerHTML = 'abcdefghi';
rowMenu.appendChild(div);
td.appendChild(rowMenu);
tr.appendChild(td);
var target = e.currentTarget;
target.parentNode.insertBefore(tr, target.nextSibling);
}
function deleteOtherMenus() {
var rowMenu = document.getElementsByClassName('row-menu-parent');
if (rowMenu.length > 0) {
rowMenu[0].parentNode.removeChild(rowMenu[0]);
}
}
* {
border: 1px solid red;
}
table {
width: 100%;
}
.row-menu div {
background-color: lightGrey;
}
<table id="table">
<tr id="hide-me">
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
What is causing my columns to move, and how do I fix it?
EDIT: The columns need to be able to automatically resize, so a fixed table layout will not work.
You can set your table to table-layout: fixed; if you don't want it resizing.
table {
table-layout: fixed; /* Add this */
width: 100%;
}
setEventListeners();
function setEventListeners() {
var hideMe = document.getElementById('hide-me');
var table = document.getElementById('table');
hideMe.addEventListener('mouseenter', showHoverMenu);
table.addEventListener('mouseleave', deleteOtherMenus);
}
function showHoverMenu(e) {
e.preventDefault();
deleteOtherMenus();
var tr = document.createElement('tr');
tr.setAttribute('class', 'row-menu-parent')
var td = document.createElement('td');
td.colSpan = 4;
var rowMenu = document.createElement('div');
rowMenu.classList.add('row-menu');
var div = document.createElement('div');
// Delete the "i" at the end of the string and try hovering again
div.innerHTML = 'abcdefghi';
rowMenu.appendChild(div);
td.appendChild(rowMenu);
tr.appendChild(td);
var target = e.currentTarget;
target.parentNode.insertBefore(tr, target.nextSibling);
}
function deleteOtherMenus() {
var rowMenu = document.getElementsByClassName('row-menu-parent');
if (rowMenu.length > 0) {
rowMenu[0].parentNode.removeChild(rowMenu[0]);
}
}
* {
border: 1px solid red;
}
table {
table-layout: fixed;
width: 100%;
}
.row-menu div {
background-color: lightGrey;
}
<table id="table">
<tr id="hide-me">
<td>A</td>
<td>B</td>
<td>C</td>
<td>D</td>
</tr>
</table>
Try setting box-sizing: border-box in CSS for the table and/or wrap the .row-menu div in a div that does not have any styling.
If you look closely, the inner div's border is expanding the size of the parent TD which is causing the table to re-adjust.
I have a very simple dynamic table search script
What I'm trying to figure out is, how do I make it search from the begining of the value?
eg. I only want it to show the row with the word london in it if one were to search it as lo or lon, currently if you type in on, or ondon it'll return true.
also with this example, how do I force it to only search the first column of each row?
$(document).ready(function() {
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').hide();
$('table tbody tr').filter(':contains("' + text + '")').show();
}
});
});
th {
cursor: pointer;
text-align: left;
}
td {
width: 100px;
}
input[type="text"] {
padding: 10px 5px;
margin: 25px 0;
font-size: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="search">
<input type="text" placeholder="search somethingn" />
</div>
<table id="items">
<thead>
<th>item</th>
<th>something else</th>
</thead>
<tbody>
<tr>
<td>london</td>
<td>test</td>
</tr>
<tr>
<td>new york</td>
<td>test 2</td>
</tr>
</tbody>
</table>
https://jsfiddle.net/8p4w62pe/
There is no built in startsWith selector, but you can write your own:
$.extend($.expr[":"], {
"startsWith": function(elem, i, data, set) {
var text = $.trim($(elem).text()),term = data[3];
return text.indexOf(term) === 0;
},
});
You will also need to change your selector to select the td (not the tr). To only select the first td add :first-child to the selector. Then change the show() to apply to the parent using parent():
$('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();
Full code:
$(document).ready(function() {
$.extend($.expr[":"], {
"startsWith": function(elem, i, data, set) {
var text = $.trim($(elem).text()),term = data[3];
return text.indexOf(term) === 0;
},
});
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').hide();
$('table tbody tr td:first-child').filter(':startsWith("' + text + '")').parent().show();
}
});
});
Working JS Fiddle
You can loop each of the row, get the first column and then hide the whole row if substring can't be found
$(document).ready(function() {
$('#search input').keyup(function() {
var text = $(this).val();
if (text != null) {
$('table tbody tr').each(function() {
if($(this).find("td:first-child").html().indexOf(text) === -1) {
$(this).hide();
}
});
}
});
});
Scenario:
I have a results table with a checkbox, when the checkbox is checked, the content of the row(actually 2 columns concateneted only, are copied to a new div, with the job code and job name). This works pretty well, and I am avoiding duplicated already.
However, in the new results div, I am creating an anchor tag to remove the div itself.
After the div has been removed, I should be able to add the selected job again with the checkbox.
Please note that there are many jobs in the results table, so putting the flag to false again will not work.
Also if you find a better title for this question, please let me know
//On every checkbow that is clicked
var flag = false;
$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
if (this.checked && flag === false) {
flag = true;
var jobCode = $(this).parent().parent().parent().find("td:eq(2)").text()
var jobName = $(this).parent().parent().parent().find("td:eq(1)").text()
var displayvalue = jobCode.toUpperCase() + " - " + jobName.toUpperCase();
AddSelectedJob(jobCode, displayvalue);
//$(this).unbind('change'); //Unbind the change event so that it doesnt fire again
FillSelectedJobs();
}
});
//Add selected job in the results div
function AddSelectedJob(id, display) {
//create a div for every selected job
$("[id$=ResultsDiv]").append('<div class="selectedjobs" id=' + id + '>' + display + 'Remove selected job</div>');
}
//Removes the selected job from the resutls div
function removeSelectedJob(el) {
$(el).parent().remove();
}
The generated html is like this:
<div>
<div style="height: 300px; overflow: auto; float: left">
<div>
<table cellspacing="0" cellpadding="4" id="ctl00_PlaceHolderMain_myGrid" style="color:#333333;width:100%;border-collapse:collapse;">
<tr style="color:White;background-color:#5D7B9D;font-weight:bold;">
<th scope="col"> </th><th scope="col">JobCode</th><th scope="col">JobName</th><th scope="col">JobPartner</th><th scope="col">JobManager</th><th scope="col">ClientName</th>
</tr><tr style="color:#333333;background-color:#F7F6F3;">
<td>
<input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1" type="checkbox" name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1" />
</td><td>jobcode01</td><td>jobname</td><td>xx</td><td>xx</td><td>xx</td>
</tr>
</table>
</div>
</div>
<div style="margin-top: 0px; margin-left: 10px; float: left">
<span>Selected :</span>
<div id="ResultsDiv" style="margin-top: 0px">
</div>
</div>
Firstly I suggest some changes to your HTML. Separate out the styles from your DOM and place them in classes.
This makes sure there is separation of concerns
HTML
<div>
<div class="divMain">
<div>
<table cellspacing="0" cellpadding="4"
id="ctl00_PlaceHolderMain_myGrid" class="table">
<tr class="rowHead">
<th scope="col"> </th>
<th scope="col">JobCode</th>
<th scope="col">JobName</th>
<th scope="col">JobPartner</th>
<th scope="col">JobManager</th>
<th scope="col">ClientName</th>
</tr>
<tr class="row">
<td>
<input id="ctl00_PlaceHolderMain_myGrid_ctl02_CheckBox1"
type="checkbox"
name="ctl00$PlaceHolderMain$myGrid$ctl02$CheckBox1"
data-flag="false" />
</td>
<td>column1</td>
<td>column2</td>
<td>column3</td>
<td>column4</td>
<td>column5</td>
</tr>
</table>
</div>
</div>
<div class="m0 selected">
<span>Selected :</span>
<div id="ResultsDiv" class="m0"></div>
</div>
CSS
.divMain{
height: 300px;
overflow: auto;
float: left
}
.table{
color:#333333;
width:100%;
border-collapse:collapse;
}
.rowHead{
color:White;
background-color:#5D7B9D;
font-weight:bold;
}
.row{
color:#333333;
background-color:#F7F6F3;
}
.m0{
margin-top: 0px;
}
.selected{
margin-left: 10px;
float: left
}
Javascript
$("#ctl00_PlaceHolderMain_myGrid input").change(function () {
// Next cache your selector
// so that you need not crawl the DOM multiple times
var $this = $(this),
$row = $this.closest('.row'),
currFlag = Boolean($this.data('flag'));
// As there might be multiple jobs , a single flag variable
// will not work. So you can set a data-flag attribute on the
// input that stores the current value
if (currFlag === false && this.checked) {
// Set the corresponding flag to true
$this.data('flag', true);
var jobCode = $row.find("td:eq(2)").text(),
jobName = $row.find("td:eq(1)").text(),
displayvalue = jobCode.toUpperCase() + " - "
+ jobName.toUpperCase(),
inputId = $this.attr('id')
// Pass the input name too as you need to set the value of
// the corresponding flag value again as you can add it multiple times
AddSelectedJob(jobCode, displayvalue, inputId);
FillSelectedJobs();
}
});
//Add selected job in the results div
function AddSelectedJob(id, display, inputId) {
//create a div for every selected job
// Use the inputId to save it as a data-id attribute
// on anchor so that you can set the value of the flag after
// removing it
var html = '<div class="selectedjobs" id=' + id + '>' + display ;
html += '<a href="javascript" data-id="'+ inputId
+'">Remove selected job</a></div>';
$('[id$=ResultsDiv]').append(html);
}
// Remove the inline click event for the anchor and delgate it to the
// static parent container
$('[id$=ResultsDiv]').on('click', 'a', function(e) {
var $this = $(this),
$currentCheckbox = $this.data('id');
// Set the flag value of the input back to false
$('#'+ $currentCheckbox).data('flag', false);
e.preventDefault(); // prevent the default action of the anchor
$this.closest('.selectedjobs').remove();
});
function FillSelectedJobs() {
//save values into the hidden field
var selectedJobs = $("[id$=ResultsDiv]").find("[class$='selectedjobs']");
var returnvalue = "";
for (var i = 0; i < selectedJobs.length; i++)
returnvalue += selectedJobs[i].id + ";";
$("[id$=HiddenClientCode]").val(returnvalue);
}
Check Fiddle