How to select the check box on button click - javascript

In the users tab there are some rows having check boxes. So if more than 2 check boxes are selected then a button named group appears.
Now when group button is clicked then then it will ask for a name and after pressing the ok button on the right side in the group table a group is created. For example select 1st and last row and click the group button. A dialog box appears asking to enter name. Enter test in the input field, after that in the right side group table test appears(please see the screenshot).
Now my question: is if I click the test(group name) now then on the left side the checkboxes will be selected. So in my case 1st check box and last check box will be selected. Please tell me how to do this. This is the fiddle
The js codes are as follows
$(function() {
$("#datetimepicker").datetimepicker({
format: "'dd/MM/yyyy hh:mm:ss'",
linkField: "#txt",
linkFormat: "yyyy-mm-dd hh:ii",
autoclose: true,
});
jQuery('#datetimepicker').datetimepicker().on('changeDate', function(ev){
$(".darea1").val($( ".darea1" ).val()+$( "#txt" ).val());
});
});
$('#tabAll').click(function(){
$('#tabAll').addClass('active');
$('.tab-pane').each(function(i,t){
$('#myTabs li').removeClass('active');
$(this).addClass('active');
});
});
$('body').on('click', '.btn', function(){
if(this.id=='openAlert') {
$('#number').val('');}else{$('#number').val(this.id);
}
});
$(document).ready(function(){
$("#signout").click(function() {
window.location.replace("logout.jsp");
});
//next line
/*var val=0;
$(document).ready(function(){
$('#btn1').click(function(){
if($(".span4").val()!="")
{
$("#mytable").append('<tr id="mytr'+val+'"></tr>');
$("#mytr"+val).append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr'+val+'" checked ></td>');
$(".span4").each(function () {
$("#mytr"+val).append("<td >"+$(this).val()+"</td>");
});
val++;
}
else
{
alert("please fill the form completely");
}
});
$('#btn2').click(function(){
var creat_group=confirm("Do you want to creat a group??");
if(val>1){
alert(creat_group);
}
});
});*/
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var email=new Array();
var username=new Array();
var mobno=new Array();
var grpname;
var creat_group = prompt("Name your group??");
grpname=creat_group;
if (creat_group) {
console.log(obj);
$("#groupTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >" + creat_group + "</td>");
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
var arrid=0;
$(this).find('td').each(function() {
//your ajax call goes here
if(count == 1){
username[arrid]=$(this).html();
}
if(count==2)
{
email[arrid]=$(this).html();
}
if(count==3)
{
mobno[arrid]=$(this).html();
}
count++;
});
arrid++;
});
$.ajax(
{
type: "POST",
url: "messageSending.jsp", //Your full URL goes here
data: { username: username, email: email,mobno:mobno,grpname:grpname},
success: function(data, textStatus, jqXHR){
alert(data);
},
error: function(jqXHR){
alert(jqXHR.responseStatus);
}
});
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//show group
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
//
});
});
//
$('#openAlert').click(function(){
var number = $('#number').val(); // If its a text input could use .text()
var msg = $('#darea').val(); //If its a text input could use .text()
alert(msg);
$.ajax(
{
type: "POST",
url: "messageSending.jsp", //Your full URL goes here
data: { toNumber: number, body: msg},
success: function(data, textStatus, jqXHR){
alert(data);
},
error: function(jqXHR){
alert(jqXHR.responseStatus);
}
});
});
});
$(function ()
{ $("#number").popover({title: 'Enter Mobile Number',content: "Please enter 10 digit mobile number prefixed by country code eg +911234567890"});
});
$(function ()
{ $("#body").popover({title: 'Message Body',content: "Maximum 160 characters allowed"});
});

Try this solution
add data-id for checkbox...set the value same as tr id or any
<tr id="46">
<td>
<input data-id="46" type="checkbox"></td>
<td>aaa</td>
jQuery
Add this lines in your code
var sCheckbox = new Array();
$('#mytable tr').find('input[type="checkbox"]:checked').each(function(i) {
sCheckbox.push($(this).attr("data-id"));
});
var ds = (sCheckbox.length > 0) ? sCheckbox.join(",") : "";
Modify this line
$tr.append("<td data-selected='"+ds+"'>" + creat_group + "</td>");
Add this event
$(document).on('click','#groupTable tr td',function () {
var dataids = $(this).attr("data-selected").split(",");
$('#mytable tr').find('input[type="checkbox"]').attr("checked",false);
$(dataids).each(function(key,dataid) {
$('#mytable tr').find('input[data-id="'+dataid+'"]').attr("checked",true);
})
});
Live Demo
Edit
Updated Demo
Add this data-id="mytr' + val + '" in checkbox element
$tr.append('<td class=\"cb\"><input data-id="mytr' + val + '" type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
note:check my inline comments in fiddle

Related

How to fetch image form its path given in the csv file to create HTML table?

I wanted the HTML table to show a specific image from its path given in the file.
csv file:
HTML Page output:
HTML code which I'm currently using.
<script>
function arrayToTable(tableData) {
var Table = $('<table></table>');
$(tableData).each(function (i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function (j, cellData) {
row.append($('<td>'+cellData+'</td>'));
});
table.append(row);
});
return Table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$('body').append(arrayToTable(Papa.parse(data).data));
}
});
</script>
I applied this script because every time I will have a variable number of rows and columns, but how to modify this script so that it will read the image address given in the col 3 and fetch those images from their path and put them in the table.
If the image is always going to be in the third column, you could do something like this.
i !== 0 is telling the browser to ignore the first row.
j === 2 is telling the browser to render the third column differently.
If the image won't always be in column 3 you could parse each string value and see if it is a image URL, but if this works it works.
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
});
function arrayToTable(tableData) {
var table = $("<table></table>");
$(tableData).each(function (i, rowData) {
var row = $("<tr></tr>");
$(rowData).each(function (j, cellData) {
if (i!==0 && j===2) {
row.append($("<td><img src='" + cellData + "'/></td>"));
return
}
row.append($("<td>" + cellData + "</td>"));
});
table.append(row);
});
return table;
}
$.ajax({
type: "GET",
url: "./img.csv",
success: function (data) {
$("body").append(arrayToTable(Papa.parse(data).data));
}
});
give an id to your table:
var Table = $('<table id="my-table"></table>');
then create an image element with the address you already have in the cell:
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
Below you can run an example with sample data:
function arrayToTable(tableData) {
var table = $('<table id="my-table"></table>');
$(tableData).each(function(i, rowData) {
var row = $('<tr></tr>');
$(rowData).each(function(j, cellData) {
row.append($('<td>' + cellData + '</td>'));
});
table.append(row);
});
return table;
}
$('body').append(arrayToTable([["asdf","qwer","https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png"]]));
$('#my-table tr').each(function( index ) {
var img_url = $( this ).children("td:last").text();
var img_element = $(document.createElement('img'))
img_element.attr('src', img_url);
$( this ).children("td:last").html(img_element);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to create a bootstrap-table dynamically?

I'm having trouble developing a bootstrap-table by clicking a button. My goal is to add a sort feature for each columns on a table. So for my user case, when a user clicks on the button, it calls an ajax to grab a data from Database and sends back a result (it works so no worries on it). So i need to display the results as a bootstrap-table so i can use the sort feature for each column. Plus, I'm using pagination.js which uses Array of json objects and table to display the result.
When I develop the table and append it into a div, I dont see the sort feature on each columns.
It works when I create a simple hard code HTML table with Bootstrap-table attributes such as sort feature (data-sortable="true"). I believe when the page loads bootstrap detects the and its attributs that is on the html body. But when I dynamically create a bootstrap-table, the HTML table is there but not the bootstrap-table feature.
Please help. Here is my code below of how i develop the table using javascript function.
// result is a large string of result when ajax is sending a response.
function displayResult(result) {
//convert the result into Array of JSON
var splitResult = result.split("*split*");
var getLast = splitResult.length - 1;
for(var i = 0; i < splitResult.length; i++){
if(i != getLast) {
splitResult[i] = JSON.parse(splitResult[i]);
} else {
splitResult.splice(i,1);
}
}
// the .pagination is a function that is use in pagination.js
// the #page is a DIV
$('#page').pagination({
dataSource: splitResult,
pageSize: 8,
callback: function(data, pagination) {
// template method
var html = template(data);
// grab the html String and append it into the #demo DIV
$("#demo").append(html);
}
})
}
function template(data) {
// table tag with bootstrap-table attributes
var html = '<table data-toggle="table" style="width: 100%;">';
// create the table headers
html = html + '<thead><tr><th data-field="IDCODE" data-sortable="true">ID</th><th scope="col" data-sortable="true">ZIP 11</th><th scope="col" data-sortable="true">Date</th></tr></thead>'
+ '<tbody>';
// input the results of the data
if (data[0].IDCODE) {
$.each(data, function(index, item) {
html += '<trid="tr-id-2" class="tr-class-2"><td>'
+ item.IDCODE+'</td>'
+ '<td>' + item.ZIP11_ID + '</td>'
+ '<td>' + item.DEL01_TS + '</td></tr>';
});
} else {
$.each(data, function(index, item) {
html += '<tr><td>'+ item +'</td></tr>';
});
}
html += '</tbody></table>';
return html;
}
when using this approach, it just display the html table. Not using bootstrap-table. I'm trying to add a feature where a user can click on the column header to sort.
Hope this code could help you, what it does is
1. display a textBox, where I user can enter a db table name
2. The backend ( in my case Python) get information from db_name_table
3. The data is displayed dinamically in the bootstrap-table
HTML
<form method="GET" id="id1" action="{% url 'request_page' %}">
<input type="text" value="db_name_table" name="mytextbox" id='mytextbox' size="1"/>
<input type="submit" class="btn" value="Click" name="mybtn">
</form>
Javascript:
$(document).ready( function(){
$('#id1').submit( function(e){
e.preventDefault();
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success:function( value ){
$('#datatable').bootstrapTable({
striped: true,
pagination: true,
showColumns: true,
showToggle: true,
showExport: true,
sortable: true,
paginationVAlign: 'both',
pageSize: 25,
pageList: [10, 25, 50, 100, 'ALL'],
columns: {{ columns|safe }},
data: {{ data|safe }},
});
}
})
})
});
$(document).ready(function() {
var i = 1;
$('#tab_logic').on('focusout', 'tbody tr:nth-last-child(2) td:nth-last-child(2) input', function() {
if ($(this).val() != '' && $('#tab_logic tbody tr:nth-last-child(2) td:nth-last-child(3) input').val() != "" && $('#tab_logic tbody tr:nth-last-child(2) .product').val() != '') {
b = i - 1;
$('#addr' + i).html($('#addr' + b).html()).find('td:first-child').html(i + 1);
$('#tab_logic').append('<tr id="addr' + (i + 1) + '"></tr>');
$(this).focus().select();
i++;
}
});
$('body').on('click', '#delete_row', function() {
if (i > 1) {
var id = i;
$('#tab_logic tbody tr:nth-last-child(2)').remove();
$('#tab_logic tbody tr:last').attr("id", "addr" + (id - 1));
i--;
}
calc();
});
$('#tab_logic tbody').on('keyup change', function() {
calc();
});
$('#tax').on('focusout', function() {
var total = parseInt($('#sub_total').val());
var tax_sum = eval(total / 100 * $('#tax').val());
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum+total).toFixed(2));
});
});
function calc() {
$('#tab_logic tbody tr').each(function(i, element) {
var html = $(this).html();
if (html != '') {
var qty = $(this).find('.qty').val();
var price = $(this).find('.price').val();
$(this).find('.total').val(qty * price);
calc_total();
}
});
}
function calc_total() {
total = 0;
$('.total').each(function() {
total += parseInt($(this).val());
});
$('#sub_total').val(total.toFixed(2));
tax_sum = total / 100 * $('#tax').val();
$('#tax_amount').val(tax_sum.toFixed(2));
$('#total_amount').val((tax_sum + total).toFixed(2));
}

VB.net non MVC RAZOR | Need help, javascript stack procress

I make a shopping website and have 2 menu, when i call page from ajax to show on my content zone (On DIV).
<script>
$(function () {
$("#chicken_tab2").click(function () {
$.ajax({
type: "POST",
url: "/view/Content/Index_cp.vbhtml",
datatype: "html",
success: function (data) {
$("#getcontent").html(data);
}
});
});
});
</script>
My content come to show but it can't use javascipt from _Layout.vbtml.
Then i put Main.js(it's Cart jquery)
<script src="~/view/Cart/main.js"></script>
inside main.js
jQuery(document).ready(function ($) {
//var getnum = $('#getnum').val();
//alert(getnum);
var cartWrapper = $('.cd-cart-container');
//product id - you don't need a counter in your real project but you can use your real product id
var productId = 0;
if( cartWrapper.length > 0 ) {
//store jQuery objects
var cartBody = cartWrapper.find('.body')
var cartList = cartBody.find('ul').eq(0);
var cartTotal = cartWrapper.find('.checkout').find('span');
var cartTrigger = cartWrapper.children('.cd-cart-trigger');
var cartCount = cartTrigger.children('.count')
var addToCartBtn = $('.cd-add-to-cart');
var undo = cartWrapper.find('.undo');
var undoTimeoutId;
var getnum = $('.getnum');
//-----------------------------------------------------------------------------------------------------
//O function Strat
//O function End
//add product to cart
addToCartBtn.on('click', function(event){
event.preventDefault();
addToCart($(this));
});
//open/close cart
cartTrigger.on('click', function(event){
event.preventDefault();
toggleCart();
});
//close cart when clicking on the .cd-cart-container::before (bg layer)
cartWrapper.on('click', function(event){
if( $(event.target).is($(this)) ) toggleCart(true);
});
//delete an item from the cart
cartList.on('click', '.delete-item', function(event){
event.preventDefault();
removeProduct($(event.target).parents('.product'));
});
//update item quantity
cartList.on('change', 'select', function(event){
quickUpdateCart();
});
//reinsert item deleted from the cart
//undo.on('click', 'a', function(event){
// clearInterval(undoTimeoutId);
// event.preventDefault();
// cartList.find('.deleted').addClass('undo-deleted').one('webkitAnimationEnd oanimationend msAnimationEnd animationend', function(){
// $(this).off('webkitAnimationEnd oanimationend msAnimationEnd animationend').removeClass('deleted undo-deleted').removeAttr('style');
// quickUpdateCart();
// });
// undo.removeClass('visible');
//});
}
function toggleCart(bool) {
var cartIsOpen = ( typeof bool === 'undefined' ) ? cartWrapper.hasClass('cart-open') : bool;
if( cartIsOpen ) {
cartWrapper.removeClass('cart-open');
//reset undo
clearInterval(undoTimeoutId);
undo.removeClass('visible');
cartList.find('.deleted').remove();
setTimeout(function(){
cartBody.scrollTop(0);
//check if cart empty to hide it
if( Number(cartCount.find('li').eq(0).text()) === 0) cartWrapper.addClass('empty');
}, 500);
} else {
cartWrapper.addClass('cart-open');
}
}
function addToCart(trigger) {
var ids = trigger.data('ids');
var item = trigger.data('item');
var cartIsEmpty = cartWrapper.hasClass('empty');
//update cart product list ****add trigger in ()
addProduct(trigger.data('item'),trigger.data('detail'), trigger.data('productname'), trigger.data('pic'), $('#' + ids + '').val());
//update number of items
updateCartCount(cartIsEmpty);
//update total price
updateCartTotal(1, true);
//show cart
cartWrapper.removeClass('empty');
}
function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d+)(\d{3})/, '$1' + ',' + '$2');
}
return val;
}
function addProduct(item, detail, product, pic, QTY) {
//this is just a product placeholder
//you should insert an item with the selected product info
//replace productId, productName, price and url with your real product info
productId = productId + 1;
//var productAdded = $('<li class="product"><div class="product-image"><img src="Cart/product-preview.png" alt="placeholder"></div><div class="product-details"><h3>'+ product +'</h3><span class="price">$'+ 1 +'</span><div class="actions">Delete<div class="quantity"><label for="cd-product-'+ productId +'">Qty</label><span class="select"><select id="cd-product-'+ productId +'" name="quantity"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option><option value="5">5</option><option value="6">6</option><option value="7">7</option><option value="8">8</option><option value="9">9</option></select></span></div></div></div></li>');
var productAdded = $('<li class="product"><div class="product-image"><input type="text" name="item" value="' + item + '" hidden /><input type="text" name="detail" value="' + detail + '" hidden /><img src="/view/images/' + pic + '" alt="placeholder"></div><div class="product-details"><h3>' + product + '</h3><input type="text" name="productname" value="' + product + '" hidden /><input type="text" name="pic" value="/view/images/' + pic + '" hidden /><span class="price">จำนวน</span><span class="price">' + QTY + ' kg.</span><input class="price" type="text" hidden name="QTY" value="' + QTY + '"><div class="actions">ลบ</div></div></li>');
cartList.prepend(productAdded);
}
function removeProduct(product) {
clearInterval(undoTimeoutId);
cartList.find('.deleted').remove();
var topPosition = product.offset().top - cartBody.children('ul').offset().top ,
productQuantity = Number(product.find('.quantity').find('select').val()),
productTotPrice = Number(product.find('.price').text().replace('$', '')) * productQuantity;
product.css('top', topPosition+'px').addClass('deleted');
//update items count + total price
updateCartTotal(1, false);
updateCartCount(true, -productQuantity);
undo.addClass('visible');
//wait 8sec before completely remove the item
undoTimeoutId = setTimeout(function(){
undo.removeClass('visible');
cartList.find('.deleted').remove();
}, 0);
}
function quickUpdateCart() {
var quantity = 0;
var price = 0;
cartList.children('li:not(.deleted)').each(function(){
var singleQuantity = Number($(this).find('select').val());
quantity = quantity + singleQuantity;
price = price + singleQuantity*Number($(this).find('.price').text().replace('$', ''));
});
cartTotal.text(price.toFixed(2));
cartCount.find('li').eq(0).text(quantity);
cartCount.find('li').eq(1).text(quantity+1);
}
function updateCartCount(emptyCart, quantity) {
if( typeof quantity === 'undefined' ) {
var actual = Number(cartCount.find('li').eq(0).text()) + 1 ;
var next = actual + 1;
if( emptyCart ) {
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
} else {
cartCount.addClass('update-count');
setTimeout(function() {
cartCount.find('li').eq(0).text(actual);
}, 150);
setTimeout(function() {
cartCount.removeClass('update-count');
}, 200);
setTimeout(function() {
cartCount.find('li').eq(1).text(next);
}, 230);
}
} else {
var actual = Number(cartCount.find('li').eq(0).text()) -1 ;
var next = actual + 1;
cartCount.find('li').eq(0).text(actual);
cartCount.find('li').eq(1).text(next);
}
}
function updateCartTotal(price, bool) {
bool ? cartTotal.text( (Number(cartTotal.text()) + Number(price)).toFixed(0) ) : cartTotal.text( (Number(cartTotal.text()) - Number(price)).toFixed(0) );
}
});
and when i change back to this page it stack a function (one time come back to this page it will do 2 time function and more if you come back again) I must to say sorry my English is not good and so thank you for help.

checkboxes and number fields set by jquery appear for a split second, then suddenly disappear

I created a simple html file that makes ajax requests to get data from a database table.
Some columns are not updated through ajax. They are manually given inputs in this page. As every ajax call refreshes the page data, I wrote storeVars() and putVars() to store the input values before refreshing and to set the stored values after refreshing respectively. But this doesn't work :(
JavaScript:
function createList() {
$.ajax({
type: "POST",
url: "fetch_registered_list.php?event_id=1",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
$('#table_data tr').not(':first').remove();
if (data != '' || data != undefined || data != null) {
var html = '';
$.each(data, function(i, item) {
html += "<tr><td>" + data[i].sno + "</td>" + "<td>" + data[i].name + "</td>" + "<td>" + data[i].email + "</td>" + "<td>" + data[i].phone + "</td>" + "<td><input class='check' name='" + i +
"' type='checkbox'/></td>" + "<td><input class='score' name='" + data[i].email + "' type='number'/></td></tr>"
})
$('#table_data tr').first().after(html);
}
}
});
}
$(document).ready(function() {
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
var checkboxes = new Array();
var scores = new Array();
function storeVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
$(this).find('.check').prop('checked', true);
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
$(this).find('.score').val('44');
});
}
HTML:
<body>
<div id="wrapper">
<div id="heading">
<h1>Event One</h1>
</div>
<form method="post">
<table id="table_data">
<tr>
<td><strong>S.no.</strong></td>
<td><strong>Name</strong></td>
<td><strong>Email</strong></td>
<td><strong>Phone</strong></td>
<td><strong>Participated</strong></td>
<td><strong>Score</strong></td>
</tr>
</table>
<footer>
<input id="button" type="button" name="submit" value="Announce Winners" />
</footer>
</form>
</div>
</body>
First, you must reset your arrays at each new storage, or you'll have arrays with exponentional new entries. Secondly your putVars() function is incorrect, it must check the values of each arrays in order to recreate the correct data in the corresponding input.
So update your document ready function to declare your two arrays.
$(document).ready(function() {
var checkboxes,
scores;
createList();
setInterval(function() {
storeVars();
createList();
putVars();
}, 5000);
});
Then reset your two arrays every storage.
function storeVars() {
checkboxes = new Array();
scores = new Array();
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function() {
checkboxes.push($(this).find('.check').is(':checked'));
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function() {
scores.push($(this).find('.score').val());
});
}
Finally update your putVars() function like this.
function putVars() {
$('#table_data tbody tr:not(:first-child) td:nth-child(5)').each(function(index) {
if(checkboxes[index] == true) {
$(this).find('.check').prop('checked', true);
}
else {
$(this).find('.check').prop('checked', false);
}
});
$('#table_data tbody tr:not(:first-child) td:nth-child(6)').each(function(index) {
$(this).find('.score').val(scores[index]);
});
}
working fiddle

how to show hidden button if more than 1 checkbox selected

I have 2 buttons add and group. Initially group button is hidden. Add button is used for creating records.
So for example:
When 5 records are created(pressing 5 times add button). Now if user selects more than
checkbox, then the hidden group button should appear. Can any body please tell me how to do this?
Please see this fiddle
I am using bootstrap css and for hiding I do as
<input type="button" id="btn2" class="btn btn-lg btn-primary hide" value="Group">
UPDATE
Check boxes will only appear if user enters some records. Filling the form and after pressing the add button
See this FIDDLE
$(document).on('change','#mytable input:checkbox',function () {
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide')
}
else {
$('#btn2').addClass('hide')
}
});
Here's the FIDDLE
if($('#mytable input:checkbox:checked').length > 1)
$('#btn2').show();
else
$('#btn2').hide();
Add a check in the change event for the checkboxes. fiddle and example below:
$(document).on('change','#mytable input:checkbox',function () {
if(!this.checked)
{
key=$(this).attr('name').replace('mytr','');
alert(key);
obj[key]=null;
}
//updated using your bootstrap class to show/hide
if($('#mytable input:checkbox:checked').length > 1) {
$('#btn2').removeClass('hide');
} else {
$('#btn2').addClass('hide');
}
});
Updated to use bootstrap class as per your updated question.
Try This
var val = 0;
var groupTrCount = 0;
$(document).ready(function () {
var obj={};
$('#btn1').click(function () {
if ($(".span4").val() != "") {
$("#mytable").append('<tr id="mytr' + val + '"></tr>');
$tr=$("#mytr" + val);
$tr.append('<td class=\"cb\"><input type=\"checkbox\" value=\"yes\" name="mytr' + val + '" unchecked ></td>');
$(".span4").each(function () {
$tr.append("<td >" + $(this).val() + "</td>");
});
var arr={};
name=($tr.find('td:eq(1)').text());
email=($tr.find('td:eq(2)').text());
mobile=($tr.find('td:eq(3)').text());
arr['name']=name;arr['email']=email;arr['mobile']=mobile;
obj[val]=arr;
val++;
} else {
alert("please fill the form completely");
}
});
$(document).on('click', '#btn2',function () {
var creat_group = confirm("Do you want to creat a group??");
if (creat_group) {
console.log(obj);
$tr.append("<td >" + groupTrCount + "</td>");
$("#groupsTable").append('<tr id="groupTr' + groupTrCount + '"></tr>');
$tr=$("#groupTr" + groupTrCount);
$tr.append("<td >Group:" + groupTrCount + "</td>"); // or you can use whatever name you want in place of "Group:"
var userColumn = "<ul>";
$('#mytable tr').filter(':has(:checkbox:checked)').each(function() {
var count=0;
$(this).find('td').each(function() {
if(count == 1){
userColumn+= "<li>" + $(this).html() + "</li>" ;
}
count++;
});
});;
userColumn+="<ul>";
$tr.append("<td >" +userColumn+ "</td>");
groupTrCount++;
}
});
$(document).on('change','#mytable input:checkbox',function () {
var rowCount = $('#mytable tr').length;
if($('input:checkbox:checked').length > 1 && rowcount > 6) {
$('#btn2').removeClass('hide')
}
});
});
Updted Fiddle is : http://jsfiddle.net/4GP9c/184/

Categories

Resources