SpringLearner
SpringLearner

Reputation: 13844

How to select the check box on button click

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"});  
});

enter image description here

Upvotes: 1

Views: 1514

Answers (1)

rynhe
rynhe

Reputation: 2529

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

Upvotes: 2

Related Questions