select all checkboxes using .map function - javascript

So, I managed to create array of ticked rows and linked it to a button. When the button is clicked, all the clicked rows will open in new tabs.
Now my problem is, I didn't manage to make everything selected .I have tried various ways of putting the selected rows into array and the one that works is this code, so i am going to stick using it:
toggleTick_Change()
var chktArr =[];
function toggleTick_Change(){
chktArr = $('.single-row-checkbox:checkbox:checked').map(function(){
return $(this).val();
}).get();
console.log('the checked values are: ' + chktArr);
$('#conditional-part').show();
}
But still didnt manage to make all selected when another checkbox is selected.
Below are the button that open to new tabs:
function btnPrintCNT_Click(){
console.log('This is from button , the checked values are: ' + chktArr);
for(let i = 0 ; chktArr.length > i ; i++){
window.open('?mod=admin&action=consignment&id=' + chktArr[i]);
}
}
Code for the checkbox HTML
<input type="checkbox" id="chkAll" value="{$rows.id}" name="chktArr" style="width: 15px; height: 15px;" class="all-row-checkbox" onchange="toggleTick_Change()" />
<input type="checkbox" id="chkT{$rows.id}" value="{$rows.id}" name="chktArr" style="width: 15px; height: 15px;" class="single-row-checkbox" onchange="toggleTick_Change()" />
Code for button HTML:
<div class="input-group " role="group" aria-label="..." style="width: 85px; margin-top: 2px; " >
<span class="input-group-btn">
<button id="btnPrintCNT" type="button" class="btn btn-sm btn-primary"
style="margin: 2px; width: 100px; margin-left: 20px; float: left;"
onclick="javascript:btnPrintCNT_Click()">CNT</button>
</span>
</div>
Any suggestion is highly appreciated.

okay, i solved it. i add if else statement correctly.
I also don't use toggleTick_Change onevent function and use class instead.
I add js-checkbox class in my checkbos html code.
below are the main thing i change in my checkboxes function
var chktArr =[];
$(document).ready(function() {
$('.js-checkbox').change(function() {
chktArr = $('.single-row-checkbox:checkbox:checked').map(function(){
return $(this).val();
}).get();
console.log('the checked values are: ' + chktArr);
$('#conditional-part').show();
if ($(this).attr('id') === 'chkAll'){
if ($(this).prop('checked') === true){
$('.single-row-checkbox').prop("checked", true);
chktArr = $('.single-row-checkbox:checkbox:checked').map(function(){
return $(this).val();
}).get();
console.log('the checked values are: ' + chktArr);
$('#conditional-part').show();
}else {
$('.single-row-checkbox').prop("checked", false);
chktArr = $('.single-row-checkbox:checkbox:checked').map(function(){
return $(this).val();
}).get();
console.log('the checked values are: ' + chktArr);
}
}else{
}
});
});
Thanks for all suggestions.

Related

How do I trigger a "cellClick" event in tabulator from javascript?

I hava a page that uses tabulator to make a table. On each row of the table I habe a small thumbnail. When I click on the thumbnail a gallery opens. I want to classify the image by clicking some buttons (yes, no etc). When I click on one buttons I want to close the gallery and then have javascript go to the next cell gallery: trigger a click on the next row's cell. I can get the cell but I cannot manage to trigger the cell click form the javascript portion. I have tried (on the cell I want to use):
//inside btn-clicked function
//after closing the gallery just want to trigger default tabulator cellClick event!
cellEl = cell.getElement();
$(cellEl).trigger('click')
and
$("document").trigger('cellClick', cell)
$("#main-table").trigger('cellClick', [cell])
None of these work.
Here is a JSFiddle: https://jsfiddle.net/q5fuon6z/
This is a totally artificial example but this demonstrates a cycle of the children when clicked.
$("#main-table").on('click', '.cell-mate', function(event) {
let cells = $('.cell-mate');
cells.toggleClass("occupied next-up", false);
$(this).toggleClass("occupied");
let myIndex = $(this).index();
let clickNext = $(this).index() == cells.last().index() ? cells.first() : $(this).next('.cell-mate');
clickNext.trigger('cellClick', [$(this), myIndex, clickNext]);
});
$('.cell-mate').on('cellClick', function(event, cell, prevIndex, nextUp) {
nextUp.toggleClass('next-up');
$('#monitor').html(cell.html() + " at " + prevIndex + " nudged " + nextUp.html() +
" at " + nextUp.index());
});
//start it all off (or comment out to start with a user action)
$("#main-table").find('.cell-mate').eq(0).trigger('click');
.occupied {
border: solid 1px #0000ff;
}
#monitor {
border: dashed 2px #ddffdd;
margin: 1em;
}
.next-up {
background-color: #ffdddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-table">
<div class="cell-mate">bunk Able</div>
<div class="cell-mate">bunk Bravo</div>
<div class="cell-mate">bunk Cat</div>
<div class="cell-mate">bunk Dog</div>
<div class="cell-mate">bunk Elephant</div>
<div class="cell-mate">bunk Giraffe</div>
</div>
<div id="monitor"></div>
Here is another example with targets specified as "next". With this example, it does not matter what order they are in since they specify a target; which I assume exists and did not account for any missing.
$("#main-table").on('click', '.cell-mate', function(event) {
let cells = $('.cell-mate');
cells.toggleClass("occupied next-up", false);
$(this).toggleClass("occupied");
let mytarget = $(this).data("nextup");
let nextOne = cells.filter(function() {
return $(this).data("iam") == mytarget;
});
let clickNext = $(this).index() == cells.last().index() ? cells.first() : $(this).next('.cell-mate');
nextOne.trigger('cellClick', [$(this), $(this).index()]);
});
$('.cell-mate').on('cellClick', function(event, cell, prevIndex) {
$(this).toggleClass('next-up');
$('#monitor').html(cell.html() + " at " + prevIndex + " nudged " + $(this).html());
});
//start it all off (or comment out to start with a user action)
$("#main-table").find('.cell-mate').eq(0).trigger('click');
.occupied {
border: solid 1px #0000ff;
}
#monitor {
border: dashed 2px #ddffdd;
margin: 1em;
}
.next-up {
background-color: #ffdddd;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="main-table">
<div class="cell-mate" data-iam="able" data-nextup="beans">bunk Able</div>
<div class="cell-mate" data-iam="g" data-nextup="able">bunk Giraffe</div>
<div class="cell-mate" data-iam="beans" data-nextup="dog">bunk Bravo</div>
<div class="cell-mate" data-iam="cat" data-nextup="elephant">bunk Cat</div>
<div class="cell-mate" data-iam="dog" data-nextup="cat">bunk Dog</div>
<div class="cell-mate" data-iam="elephant" data-nextup="g">bunk Elephant</div>
</div>
<div id="monitor"></div>
Apparently the correct syntax for tabulator is:
$(cell.getElement()).trigger('click')

Nested events triggered multiple times

I have a question about a code like the following:
$(function() {
var checkboxCnt = 1;
var checkboxHtml =
`<br><input type="checkbox" id="checkbox${checkboxCnt}">` +
`<label for="checkbox${checkboxCnt}">Checkbox 1</label>`;
// ******************************************
$('div :checkbox').change(function(e) {
checkboxChanged(e);
});
// ******************************************
$('#btn').click(function() {
checkboxCnt++;
checkboxHtml = checkboxHtml.replaceAll(checkboxCnt - 1, checkboxCnt);
$(this).before($(checkboxHtml));
// ******************************************
$('div :checkbox').change(function(e) {
checkboxChanged(e);
});
// ******************************************
});
function checkboxChanged(e) {
var checkboxID = '#' + e.target.id;
if ($(checkboxID).is(':checked')) {
console.log(checkboxID + ' is checked');
} else {
console.log(checkboxID + ' is unchecked');
}
}
});
#btn {
width: 100px;
height: 100px;
background-color: yellow;
display: block;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<div>
<input type="checkbox" id="checkbox1">
<label for="checkbox1">Checkbox 1</label>
<button type="button" id="btn">Click Me!</button>
</div>
Sample can be found on https://jsfiddle.net/da7wLukz/.
This is just a simplified version of the code I'm currently editing, and it adds a checkbox every time when you hit the button. I want to execute something every time when the checkboxes are (un)checked, but I've come across the problem that when you have 4 checkboxes and check the checkbox4, the change event is triggered only once but when you check the checkbox3, it's triggered twice, and when you check the checkbox2, it's triggered 3 times and so on. The code has the same lines inside and outside of $('#btn).click because, let's say we don't have the $('div :checkbox).change event inside the $('#btn).click event, then the change event isn't triggered when checkbox2, 3, 4... are checked.
I just want the change event to be triggered only once when I (un)check the checkbox, but how can I do this? Thank you for your help in advance.
Don't nest event handlers. Use unobtrusive event handling via $(document).on() (docs):
$(function() {
var checkboxCnt = 0;
var checkboxHtml =
`<input type="checkbox" id="checkbox$%%">` +
`<label for="checkbox$%%">Checkbox %%</label><br>`;
function addCheckbox() {
checkboxCnt++;
$("#btn").before(checkboxHtml.replaceAll('%%', checkboxCnt));
}
$(document).on('change', 'div :checkbox', function () {
if (this.checked) {
console.log(this.id + ' is checked');
} else {
console.log(this.id + ' is unchecked');
}
});
$('#btn').click(addCheckbox);
addCheckbox();
});
#btn {
width: 100px;
height: 100px;
background-color: yellow;
display: block;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.js"></script>
<div>
<button type="button" id="btn">Click Me!</button>
</div>

how to clone div value to input

I need to copy a value from a "Div" to an "input" by clicking the button.
the function is copying the whole div html value, contrary to what i need, i want to copy only the text.
view example: https://jsfiddle.net/fg79vypb/
$('#copy').on('click', function() {
$('#message').val($('<div/>').append($('#whatsapp').clone()).html());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="copy">Get order on WhatsApp</button>
<div id="whatsapp" style=" position: fixed; width: 200px; height: auto; bottom: 40px; right: 40px; background-color: #e0ffe7; border-radius: 10px; padding-left: 10px; border-top-width: 10px; padding-top: 10px; padding-bottom: 10px;"><span class="simpleCart_total">R$ 18.00</span> (<span class="simpleCart_quantity" id="simpleCart_quantity">1</span> items)
<br><br>
<div class="simpleCart_items"><div class="cartHeaders"><div class="itemName">Name</div><div class="itemPrice">Price</div><div class="itemQuantity">Quantity</div><div class="item"></div></div><div class="itemContainer"><div class="itemName">Product name 1</div><div class="itemPrice">R$ 18.00</div><div class="itemQuantity">1</div><div class="item"> </div></div></div>
<a class="simpleCart_empty" href="javascript:;">clean cart</a>
<br><br>
<a class="simpleCart_checkout" href="javascript:;">go to checkout</a></div>
<input id="message" type="text" >
I would like to get only the text value, and is displaying all html code.
This code will do what you want. Just copy text not html code
$('#copy').on('click', function() {
$('#message').val($('#whatsapp').text());
});
Here is an example of how to capture all item names and their prices and place them into an array using JQuery. You can then decide what you want to do with them from there:
let items = []; //Declare an array which will hold all items selected by user
let valueForTextbox = "";
//Iterate each name and grab it's corresponding price:
$('.itemName').each(function(){
//Check for the header row, so we don't place titles into the array
if($(this).text() !== 'Name'){
items.push({ ItemName: $(this).text(), ItemPrice: $(this).next('.itemPrice').text() });
}
});
//Display each item's name and price
items.forEach(function(item){
//Concat the item names and item prices
valueForTextbox += item.ItemName + " " + item.ItemPrice + " ");
});
//Set the textbox value
$('#message').val(valueForTextbox);
//You can then format each item to whatever you need from here

Checkboxes not binding to tags they create on DOM jquery

I have created a modal with checkboxes that when checked, are added to the DOM. The issues that I am having that I have been trying to troubleshoot for days are that whether the checkboxes are checked or unchecked, the tag is added to the DOM, not just when checked.
I also cannot figure out how to remove the tag from the DOM when the associated checkbox is unchecked. I have the amount of checkboxes that are able to be checked max out at 6, which is what I am looking to have, but is there a way to max the amount of child divs within a parent div there could be? That way theres another safeguard to fall back on so that no more than 6 tags can be selected at one time?
Here is a jsfiddle http://jsfiddle.net/co5w7c9j/ with what I have, hopefully I explained enough without making it sound too confusing.
Below is my jquery that I have written thus far, I think I am missing a step somewhere to achieve what I am looking for.
Thank you for taking the time to look through my code.
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
/* if ($('.Specialties > .specTag').has(('[name=specialty]:checked').attr('value'))) {
$('.Specialties > .specTag').has((this).txt()).remove();
} */
// Count number of checkboxes selected and display in modal
var increment = 0;
$('[name=specialty]:checked').each(function() {
if (this.checked) {
increment++;
} else {
increment--;
}
$('#specCount').html(increment);
});
// Disable checkboxes when 6 (maximum) are selected
$("input[type=checkbox][name=specialty]").click(function() {
var bol = $("input[type=checkbox][name=specialty]:checked").length >= 6;
$("input[type=checkbox][name=specialty]").not(":checked").attr("disabled", bol);
});
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function() {
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
});
Try
// When specilaty is checked, add tag to profile page
$('input[name=specialty]').change(function() {
var value = this.value;
//if checked add a new item else remove item.
if (this.checked) {
var $newTag = $("<div class='specTag'>" + value + "<div class='xOut'>x</div></div>").attr('data-id', value);
$('.Specialties').append($newTag);
} else {
//use the attribute value which is the same as the input value to find out the item to be removed
$('.Specialties').find('div.specTag[data-id="' + value + '"]').remove()
}
//cache the result since it is used multiple times
var $checked = $('input[name=specialty]:checked');
// Count number of checkboxes selected and display in modal
var increment = $checked.length;
$('#specCount').html(increment);
// Disable checkboxes when 6 (maximum) are selected
var bol = increment.length >= 6;
//use prop instead of attr to set the disabled state
$("input[type=checkbox][name=specialty]").not(":checked").prop("disabled", bol);
// Create array of checked items - add on checked - remove on uncheck
var specialtyArray = $checked.map(function() {
return $(this).val();
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function() {
$('.modal-body > #updateSpecForm > .columns').children().prop('checked', false);
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function() {
$(this).parent().fadeOut('slow', function() {
$(this).remove();
});
//uncheck the corresponding checkbox
$('input[name=specialty][value="' + $(this).closest('.specTag').attr('data-id') + '"]').prop('checked', false)
});
.Specialties {
background-color: #FFFFFF;
width: 350px;
height: 135px;
margin-left: 249px;
margin-top: 125px;
top: 0;
position: absolute;
z-index: 1;
}
.specTag {
background-color: #51b848;
color: #FFFFFF;
font-weight: 200;
letter-spacing: 1px;
font-size: 12px;
width: 150px;
height 30px;
padding: 8px;
position: relative;
margin-left: 10px;
margin-bottom: 5px;
border-radius: 5px;
display: inline-block;
}
.xOut {
background-color: #FFFFFF;
width: 25px;
padding: 3px;
position: absolute;
right: 5px;
text-align: center;
color: #333333;
top: 5px;
border-radius: 0 3px 3px 0;
cursor: pointer;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="GET" id="updateSpecForm">
<!-- ATHLETIC TRAINER OPTIONS -->
<div class="columns" id="athleticTrainer">
<input type="checkbox" name="specialty" value="Boot Camp" />Boot Camp
<br />
<input type="checkbox" name="specialty" value="Children's Fitness" />Children's Fitness
<br />
<input type="checkbox" name="specialty" value="Circuit Training" />Circuit Training
<br />
<input type="checkbox" name="specialty" value="Core Training" />Core Training
<br />
<input type="checkbox" name="specialty" value="Cycling/Spinning" />Cycling/Spinning
<br />
<input type="checkbox" name="specialty" value="Dance" />Dance
<br />
<input type="checkbox" name="specialty" value="Flexibility/Balance" />Flexibility/Balance
<br />
<input type="checkbox" name="specialty" value="Meal Planning" />Meal Planning
<br />
<input type="checkbox" name="specialty" value="Men's Fitness" />Men's Fitness
<br />
<input type="checkbox" name="specialty" value="Women's Fitness" />Women's Fitness
<br />
</div>
<div class="Specialties">
<!-- SHOW BELOW DIV ONLY IF LOGGED IN -->
<!-- <div class="updateOn">+ Update My Specialties</div> -->
<!-- ***PRO CAN ADD UP TO 6 SPECIALY TAGS*** -->
</div>
</form>
Sometimes it's easier to compartmentalize code by setting parts of it into functions so that conditional aspects are easier to read through .
The biggest issue in your code was not testing if checkboxes were checked or not in the click handler.
Since the checkbox needs to do the same as the click on new tag does when it is unchecked, all logic flows through the change event of checkbox. Note that the click handler on X of tag triggers the change also
var maxChecked = 6;
// use change handler on checkboxes, will get triggered also below in another click handler
var $checkboxes = $('[name=specialty]').change(function() {
var value = $(this).val();
if(this.checked ){
addTag( value);
}else{
removeTag( value );
}
checkBoxStatus();
});
function removeTag(checkBoxValue){
/* we stored the checkbox value as data attribute, use that to filter*/
$('.specTag').filter(function(){
return $(this).data('value') === checkBoxValue;
}).slideUp(function(){
$(this).remove();
})
}
function addTag( checkBoxValue){
$newTag = $("<div class='specTag'>" + checkBoxValue + "<div class='xOut'>x</div></div>");
/* store the value in elment data so we can reference back to checkbox */
$newTag.data('value', checkBoxValue);
$('.Specialties').append($newTag);
}
/* use this to both disable and enable checkboxes */
function checkBoxStatus(){
var limitReached = $checkboxes.filter(':checked').length === maxChecked;
$checkboxes.not(':checked').prop('disabled',limitReached);
}
$(document.body).on('click', '.xOut', function () {
var $element = $(this).parent(),
$checkbox = $checkboxes.filter(function(){
return this.value === $element.data('value');
/* trigger change to remove element and reset disabled checkboxes */
}).prop('checked',false).change();
});
DEMO
Working fiddle:
http://jsfiddle.net/co5w7c9j/1/
// When specilaty is checked, add tag to profile page
$('[name=specialty]').click(function() {
$newTag = $("<div class='specTag'>" + $(this).attr('value') + "<div class='xOut'>x</div></div>");
$(this).attr('value');
$('.Specialties').append($newTag);
EnableDisableCheck();
// Create array of checked items - add on checked - remove on uncheck
specialtyArray = $('[name=specialty]:checked').map(function(){
return $(this).val();
// if item is in the array, then remove it from the DOM
if (jQuery.inArray($('[name=specialty]:checked').val(), specialtyArray) > -1) {
}
});
console.log(specialtyArray.get());
});
// When Specialties modal closes, uncheck all checked boxes, reset count
$(document.body).on('click', '.close', function () {
$('.modal-body > #updateSpecForm > .columns').children().removeAttr('checked');
$('#specCount').html(0);
})
// Fade out specialty tags when x is clicked
$(document.body).on('click', '.xOut', function () {
$(this).parent().fadeOut('slow');
$(this).parent().remove();
var text = $(this).parent().text();
$('[name=specialty]:checked').filter(function () {
return text.indexOf($(this).val()) > - 1;
}).removeAttr('checked');
EnableDisableCheck();
});
function EnableDisableCheck(){
if($('[name=specialty]:checked').length >=5)
{
$('[name=specialty]').attr("disabled","disabled");
}
else
{
$('[name=specialty]').removeAttr("disabled");
}
}

Add and remove checkbox events dynamically depending on some business logic?

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

Categories

Resources