I am generating a table based on user input. Finding the table cell index on click function. I am trying to include a alert with radio buttons. On click of cells alert will be generate and that alert box should have radio buttons. I tried this but something went wrong.
function CreateTable() {
var rowCtr;
var cellCtr;
var rowCnt;
var cellCnt;
var myTableDiv = document.getElementById("myDynamicTable");
var table = document.createElement('Table');
table.setAttribute("contenteditable", "true");
table.border = '1';
table.id = 'myTable';
var tableBody = document.createElement('Tbody');
table.appendChild(tableBody);
rowCnt = document.getElementById('txtrows').value;
cellCnt = document.getElementById('txtcols').value;
for (var rowCtr = 0; rowCtr < rowCnt; rowCtr++) {
var tr = document.createElement('tr');
tableBody.appendChild(tr);
for (var cellCtr = 0; cellCtr < cellCnt; cellCtr++) {
var td = document.createElement('td');
td.width = '120';
td.appendChild(document.createTextNode("Click me," + rowCtr + +cellCtr));
tr.appendChild(td);
}
}
myTableDiv.appendChild(table);
CellIndex();
}
function CellIndex() {
$(document).ready(function() {
$('#myTable').on('click', 'td', function() {
var columnIndex = $(this).parent().find('td').index(this);
var rowIndex = $(this).parent().parent().find('tr').index($(this).parent());
//alert('ColumnIndex' + " " + columnIndex + 'RowIndex' + rowIndex);
var popUpList = $('<input type="radio">Insert Before<br><input type="radio">Insert After');
alert('popuplist' + popUpList);
});
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table contenteditable="true">
<tr>
<td>Row Count</td>
<td>Column Count</td>
<td></td>
</tr>
<tr>
<td><input type="text" id="txtrows" /></td>
<td><input type="text" id="txtcols" /></td>
<td><button onclick="CreateTable()">Create Table</button></td>
</tr>
</table>
<div id="myDynamicTable"></div>
An alert() is a graphical component generated and rendered by the browser (client) software. It's not part of the web page and is not capable of rendering HTML inside of it - only plain text.
You can, however get the result you want by building your own dialog out of HTML and CSS and keeping it hidden until needed. When that occurs, you can show it via JavaScript.
Here's an example:
let selectedColor = "";
// Get DOM references to elements we'll want to refer to multiple times
let dialog = document.getElementById("dialog");
let result = document.getElementById("result");
let mask = document.getElementById("mask");
// Set up event handlers for the buttons
document.getElementById("show").addEventListener("click", function(){
mask.classList.remove("hidden"); // Show the mask
dialog.classList.remove("hidden"); // Show the dialog
});
document.getElementById("hide").addEventListener("click", function(){
mask.classList.add("hidden"); // Hide the mask
dialog.classList.add("hidden"); // Hide the dialog
result.textContent = "You chose: " + selectedColor;
});
// Set up event listener on dialog for radio button clicks
dialog.addEventListener("click", function(event){
// If the source of the click was a radio button, capture its value
if(event.target.type === "radio"){
selectedColor = event.target.value;
}
});
.hidden { display:none; } /* used by the dialog by default */
/* When the dialog is shown, the mask will cover the main web page */
#mask {
position:absolute;
background-color:rgba(0,0,0,.25);
top:0;
left:0;
right:0;
bottom:0;
z-index:1; /* This layers the mask on top of the main web page content. */
}
/* Style the dialog and the elements in it as you wish */
#dialog {
position:absolute; /* So the dialog can be in its own layer and placed anywhere we want */
top:20%;
left:25%;
border:10px double #222;
background-color:aliceblue;
padding:10px;
width:50%;
height:125px;
text-align:center;
z-index:10; /* Make sure the dialog is in the top layer */
}
#dialog > h1 {
margin-top:0;
}
#dialog > footer {
margin-top:1.5em;
}
#result {
text-align:center;
font-weight:bold;
font-size:2em;
margin:2em;
}
<input type="button" value="Show Dialog" id="show">
<!-- This div will be as big as the entire page and it will be layered
in front of the main content, but under the dialog, creating a "modal" effect -->
<div id="mask" class="hidden"></div>
<div id="dialog" class="hidden">
<h1>Please pick a color</h1>
<div>
<label><input type="radio" name="color" value="red">Red</label>
<label><input type="radio" name="color" value="white">White</label>
<label><input type="radio" name="color" value="blue">Blue</label>
</div>
<footer>
<input type="button" value="Hide Dialog" id="hide">
</footer>
</div>
<div id="result"></div>
Natively, with the Window Object Methods, you only can:
Displays an alert box with a message and an OK button - Window alert() Method
Displays a dialog box with a message and an OK and a Cancel button - Window confirm() Method
Displays a dialog box with a message and an OK and a Cancel button - Window prompt() Method
HTML has to be used inside a Form into the body of the document.
Related
I am in the process of creating a website and I have a HTML table that you can add a row to by clicking a button. There is an input box for every column in every row. When the table is submitted, it should retrieve all the info from all the input boxes and put it in an array that separates the rows.
I am positive that this requires a loop and I tried getting the children from the tbody element, but that didn't return the correct values.
function submitForm() {
var c = $("#tbl").children;
console.log(c);
}
it's very simple, just browse the rows of the array and the cells of each line.
So obviously I do not know what type of array you want, but I've made you here an example of a array with Jquery.
I hope it will help you.
$(function(){
var datas = [];
$.each($('#table tr'), function(index, val) {
var childs = $(this).children('td');
var array = {childs: []};
$.each(childs, function(i, v) {
//get your value
var value = $(this).text();
array.childs.push(value);
});
datas.push(array);
});
//final result
console.log(datas);
});
<!DOCTYPE html>
<html>
<head>
<title>Resultat</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<div>
<table id="table" border="1">
<tr>
<td>Value1 line1</td>
<td>Value2 line1</td>
<td>Value3 line1</td>
</tr>
<tr>
<td>Value1 line2</td>
<td>Value2 line2</td>
<td>Value3 line2</td>
</tr>
<tr>
<td>Value1 line3</td>
<td>Value2 line3</td>
<td>Value3 line3</td>
</tr>
</table>
</div>
</body>
</html>
Here is a simplified solution you could easily work into your form submission code.
const tdInputs = document.querySelectorAll('td > input');
let inputValues = [];
tdInputs.forEach(input => inputValues.push(input.value));
console.log(inputValues);
<table>
<tr>
<td><input type="text" value="value1"></td>
</tr>
<tr>
<td><input type="text" value="value2"></td>
</tr>
</table>
http://jsfiddle.net/xpvt214o/1022151/
Assuming...
Since there's hardly any code in the question, I took the liberty to add what I consider necessary to which the question neglected to provide. If you don't have the setup like how my demo is setup, I recommend that you consider refactoring your code a little.
Setup
The demo is fully functional:
Adds and removes rows
A <form> is wrapped around the <table> since there's an <input> in each <td>
The <form> will send its data to a live test server when the submit event is triggered.
The live server will send a response as a JSON which will be displayed in the <iframe> located below the <table>.
This default behavior triggered by asubmit event will be temporarily postponed by this function:
// Earlier in the code, this was called to interrupt the default behavior
event.preventDefault();
...
/* .map() all inputs in the table...
| store all the strings that contain an input's name and value into a jQuery Object
| .get() the data from the jQuery Object as an array
| although optional, you can present it as a string by using `.join()`
*/// Finally, submit the form data to the test server
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
/**/
Demo
var count = 0;
var row = `<tr><td><input name='a'></td><td><input name='b'></td><td><input name='c'></td><td><button class='del' type='button'>➖</button></td></tr>`;
$('.ui').on('click', 'button', function(e) {
e.preventDefault();
if ($(this).hasClass('add')) {
count++;
$('.data').append(row);
$('tr:last input').each(function() {
var name = $(this).attr('name');
$(this).attr('name', name+count);
});
} else if ($(this).hasClass('del')) {
$(this).closest('tr').remove();
} else {
var dataArray = $('.data input').map(function(idx, txt) {
return `${$(this).attr('name')}: ${$(this).val()}`;
}).get().join(', ');
console.log(JSON.stringify(dataArray));
$('.ui').submit();
}
});
.ui {width: 100%}
.set {padding: 0;}
.data {width: 100%; table-layout: fixed; border: 1px ridge #777; border-spacing: 1px}
td {width: 30%; padding: 0 1px}
tr td:last-of-type {width: 10%}
.add {margin: 0 0 0 85%;}
iframe {width: 100%}
.as-console-wrapper.as-console-wrapper {
max-height: 20%;
}
.as-console-row.as-console-row::after {
content:'';
padding:0;
margin:0;
border:0;
width:0;
}
<form class='ui' action='https://httpbin.org/post' method='post' target='response'>
<fieldset class='set'>
<button class='add' type='button'>➕</button>
<button>🡺</button>
</fieldset>
<table class='data'>
<tr><td><input name='a0'></td><td><input name='b0'></td><td><input name='c0'></td><td><button class='del' type='button'>➖</button></td></tr>
</table>
</form>
<iframe src='about:blank' name='response'></iframe>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I having issue with modal in headers. When i click header "Safety", it open safety's modal and have manage to add item ONE ROW EVERY CLICK, which is great. When i duplicate my codes for second header, which is "Operate". The issue started.
After i open Safety's modal, added new item and close the modal, I open Operate's modal and add new item. The new item i added is not ONE ROW EVERY CLICK, it added TWO Row EVERY CLICK and sometimes THREE ROW EVERY CLICK.
Please help.
// Get the that opens the Safety NewsFeed
var s_news = document.getElementById('s_news');
var safety = document.getElementById('Safety');
safety.onclick = function() {
s_news.style.display = "block";
$('.AddNew').click(function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row).removeClass('AddNew').addClass('RemoveRow').val('Remove item');
});
$('table').on('click', '.RemoveRow', function() {
$(this).closest('tr').remove();
});
}
// Get the <span> element that closes the modal
var snews_span = document.getElementsByClassName("s_newsclose")[0];
// When the user clicks on <span> (x), close the modal
snews_span.onclick = function() {
s_news.style.display = "none";
}
// Close Safety NewsFeed
window.addEventListener("click", function(s_newsevent) {
if (s_newsevent.target == s_news) {
s_news.style.display = "none";
}
});
///
// Get the that opens the Quality Internal NewsFeed
var qi_news = document.getElementById('qi_news');
var qualityint = document.getElementById('QualityInt');
qualityint.onclick = function() {
qi_news.style.display = "block";
$('.AddNew').click(function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row).removeClass('AddNew').addClass('RemoveRow').val('Remove item');
});
$('table').on('click', '.RemoveRow', function() {
$(this).closest('tr').remove();
});
}
// Get the <span> element that closes the modal
var qinews_span = document.getElementsByClassName("qi_newsclose")[0];
// When the user clicks on <span> (x), close the modal
qinews_span.onclick = function() {
qi_news.style.display = "none";
}
// Close Safety NewsFeed
window.addEventListener("click", function(qi_newsevent) {
if (qi_newsevent.target == qi_news) {
qi_news.style.display = "none";
}
});
/* News Feed (background) */
.s_news,
.qi_news {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.9);
/* Black w/ opacity */
}
.headercolor {
background-color: rgba(255, 0, 0, 1);
}
/* The Newsfeed Close Button */
.s_newsclose,
.qi_newsclose {
color: #aaa;
float: left;
font-size: 28px;
font-weight: bold;
}
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<h2 style="font-size:1.5rem" id=Safety>Safety</h2>
<h2 style="font-size:1.5rem" id=QualityInt>Operate</h2>
<div id="s_news" class="s_news">
<table>
<tr>
<td class=headercolor>ISSUE</td>
<td class=headercolor>ACTION</td>
<td class=headercolor>Add/Remove Item</td>
</tr> <span class="s_newsclose">×</span>
<tr>
<td><input type='text' value='Add New'></td>
<td><input type='text' value='Add New'></td>
<td><input type='button' class='AddNew' value='Add new item'></td>
</tr>
</table>
</div>
<div id="qi_news" class="qi_news">
<table>
<tr>
<td class=headercolor>ISSUE</td>
<td class=headercolor>ACTION</td>
<td class=headercolor>Add/Remove Item</td>
</tr> <span class="qi_newsclose">×</span>
<tr>
<td><input type='text' value='Add New'></td>
<td><input type='text' value='Add New -->'></td>
<td><input type='button' class='AddNew' value='Add new item'></td>
</tr>
</table>
</div>
</body>
</html>
Examine the code nested within the safety.onclick code block. Each time you click "Safety", you're binding a jQuery click() event handler to all elements that have a class attribute of AddNew. You can see this for yourself in the code snippet you provide. Click the header, and immediately close it. Repeat two more times. Now when you click the "Add Item" button you'll see that three new rows display.
Also, notice how the effect you want to achieve is the same for each of your divs. I would recommend a more DRY approach to your code here. Consider an alternative solution where your jQuery event bindings utilize the .on() method and are not nested within the vanilla onclick handler.
$('#s_news, #qi_news').on('click', '.AddNew', function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row)
.removeClass('AddNew')
.addClass('RemoveRow')
.val('Remove item');
});
$('#s_news, #qi_news').on('click', '.RemoveRow', function() {
$(this).closest('tr').remove();
});
Here's an example of implementing the add/remove event handling code: https://jsfiddle.net/v5r2f913
One more bit of general commentary on the provided code sample: since you are using jQuery, you may consider just using that library's selectors and event model, rather than a mixture of jQuery and vanilla JavaScript.
The problem is that your .AddNew class is getting call more than once. Just change the name of the class that targets the click event on both (Safety and Operate). Example: change the first class to ".AddNew1" and the second one to ".AddNew2".
Here's a working solution. Hope it helps!
// Get the that opens the Safety NewsFeed
var s_news = document.getElementById('s_news');
var safety = document.getElementById('Safety');
safety.onclick = function() {
s_news.style.display = "block";
$('.AddNew1').click(function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row).removeClass('AddNew').addClass('RemoveRow').val('Remove item');
});
$('table').on('click', '.RemoveRow', function() {
$(this).closest('tr').remove();
});
}
// Get the <span> element that closes the modal
var snews_span = document.getElementsByClassName("s_newsclose")[0];
// When the user clicks on <span> (x), close the modal
snews_span.onclick = function() {
s_news.style.display = "none";
}
// Close Safety NewsFeed
window.addEventListener("click", function(s_newsevent) {
if (s_newsevent.target == s_news) {
s_news.style.display = "none";
}
});
///
// Get the that opens the Quality Internal NewsFeed
var qi_news = document.getElementById('qi_news');
var qualityint = document.getElementById('QualityInt');
qualityint.onclick = function() {
qi_news.style.display = "block";
$('.AddNew2').click(function() {
var row = $(this).closest('tr').clone();
row.find('input').val('');
$(this).closest('tr').after(row);
$('input[type="button"]', row).removeClass('AddNew').addClass('RemoveRow').val('Remove item');
});
$('table').on('click', '.RemoveRow', function() {
$(this).closest('tr').remove();
});
}
// Get the <span> element that closes the modal
var qinews_span = document.getElementsByClassName("qi_newsclose")[0];
// When the user clicks on <span> (x), close the modal
qinews_span.onclick = function() {
qi_news.style.display = "none";
}
// Close Safety NewsFeed
window.addEventListener("click", function(qi_newsevent) {
if (qi_newsevent.target == qi_news) {
qi_news.style.display = "none";
}
});
.s_news,
.qi_news {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.9);
/* Black w/ opacity */
}
.headercolor {
background-color: rgba(255, 0, 0, 1);
}
/* The Newsfeed Close Button */
.s_newsclose,
.qi_newsclose {
color: #aaa;
float: left;
font-size: 28px;
font-weight: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h2 style="font-size:1.5rem" id=Safety>Safety</h2>
<h2 style="font-size:1.5rem" id=QualityInt>Operate</h2>
<div id="s_news" class="s_news">
<table>
<tr>
<td class=headercolor>ISSUE</td>
<td class=headercolor>ACTION</td>
<td class=headercolor>Add/Remove Item</td>
</tr> <span class="s_newsclose">×</span>
<tr>
<td><input type='text' value='Add New'></td>
<td><input type='text' value='Add New'></td>
<td><input type='button' class='AddNew1' value='Add new item'></td>
</tr>
</table>
</div>
<div id="qi_news" class="qi_news">
<table>
<tr>
<td class=headercolor>ISSUE</td>
<td class=headercolor>ACTION</td>
<td class=headercolor>Add/Remove Item</td>
</tr> <span class="qi_newsclose">×</span>
<tr>
<td><input type='text' value='Add New'></td>
<td><input type='text' value='Add New -->'></td>
<td><input type='button' class='AddNew2' value='Add new item'></td>
</tr>
</table>
</div>
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>
I want to change the paragraphs visibility to none or hidden dynamicly using javascript.I have 4 paragraphs and I want only one to be displayed.If a user clicks right button the next parargraph should be displayed instead of the previous one.If left button, then another way.But my event handlers don't seem to respond inside the paragrap_switch function.Please help me with that
HTML
<head>
<style>
p{
border:1px solid black;
width:20%;
display:none;
}
input{
width:40px;
}
</style>
</head>
<body>
<p class="paragraph">TEXT 1</p>
<p class="paragraph">TEXT 2</p>
<p class="paragraph">TEXT 3</p>
<p class="paragraph">TEXT 4</p>
<input type = "button" value = "left" class = "button"/>
<input type = "button" value = "right" class = "button"/>
And Javascript
function paragraph_switch (){
var paragraphs = document.getElementsByClassName('paragraph');
var buttons = document.getElementsByClassName('button');
for(var i = 0;i < paragraphs.length; i++){
if(i >= 0){
if(buttons[0].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i+1].style.display = "block";
i++;
}
else if(buttons[1].onclick = function(){
paragraphs[i].style.display = "none";
paragraphs[i-1].style.display = "block";
i--;
}
}
}
}
I am not sure what your code is doing. You are assigning eventhandler inside the if condition.
I have implemented your requirement using jQuery. Here is the jsfiddle.
http://jsfiddle.net/DyZf2/
Here is the js code.
$("p:first").show();
$("#left").click(function(){
$("p:visible").hide().prev().show();
});
$("#right").click(function(){
$("p:visible").hide().next().show();
});
You may have to modify the code to make sure that next/previous paragraph exists before hiding the current one.
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