how to show hidden button if more than 1 checkbox selected - javascript

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/

Related

Disable unchecked check boxes in selected div element using jquery

I am creating check boxes dynamically using jquery. I want to disable unchecked check boxes as shown in the snippet,but i want to disable the check boxes only in their respective div elements and not in the other div elements which is what causing issue now.
I have written the code to disable/enable checkboxes based on their respective div tags and i have commented it as it is throwing error if enabled.
$($(".checkbox").eq(id).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Problem explanation : Here i am creating two div tags dynamically inside which check boxes are also created with same name. So if i check on checkbox in first div other checkbox gets disabled and other div tag gets created which works as expected. but if i check any option in second div tag other option in second div tag doesn't get disabled and also if i uncheck the checked option in first div tag both options get disabled in first div tag. I guess this is because all checkboxes have same names.
How can we disable checkboxes only in their respective div tags. I tried below code but didn't work
$($(".checkbox").eq(1).":checkbox[name='radio']:not(:checked)").prop('disabled', true);
Below snippet explains the problem more appropriately
Please help me.
function checkdiv(id, val) {
if ($(":checkbox[name='radio']:checked").length == 1)
$(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>
Have you tried ".find" in the jQuery API - this will only find elements within the specified selector - see the modifications to the "checkdiv" function ($('#' + id))
function checkdiv(id, val) {
if ($('#' + id).find(":checkbox[name='radio']:checked").length == 1)
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', true);
else
$('#' + id).find(":checkbox[name='radio']:not(:checked)").prop('disabled', false);
var diva = Number(id) + 1;
var divb = Number(id) + 1;
//if(id.length != 0){
if (val.checked == true) {
if (diva < 2 && divb < 2) {
creatediv('maindiv')
}
}
// }
else {
var diva = Number(id) + 1;
var divb = Number(id) + 1;
$("#" + diva).remove();
$(".divot").eq(divb).remove();
}
}
function creatediv(main) {
var divid = $(".divin").length;
var divid1 = $(".divot").length;
var div = "<div class='col-xs-2 divin' id='" + divid + "' style='border:1px solid'><span class='header'></span></div><div class='col-xs-1 divot'></div>";
$('#' + main).append(div);
loadval(divid)
}
function loadval(div) {
var div1 = "<div class='checkbox'><label><input type='checkbox' name='radio' value='Head' onchange='checkdiv(" + div + ",this)'>Head</label><br><label><input type='checkbox' name='radio' value='Hand' onchange='checkdiv(" + div + ",this)'>Hand</label></div>";
$("#" + div).append(div1)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body onload="creatediv('maindiv')">
<div class="container">
<div class="form-group row" id="maindiv">
</div>
</div>
</body>

Cannot select a button which appended dynamically in jQuery

I use getJSON function in jQuery and append the retrieved result in the form of button in the DOM. however I cannot use the selector on the appended DOM.
here is my script:
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
})
this is what i use to select:
$(':button.diaries').click(function(){});
but it seems not working. however when I put a dummy button with the same class in the HTML body, it is selected perfectly. Can you guys give me any suggestion?
#Kelvin Aliyanto ....So the solution will be like this
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script>
$(function(){
$.getJSON("http://example.com/checkDiary.php?babyID=" + localStorage.getItem("babyRegNo"), function(data) {
if (data.indexOf("noDiary") > -1) {
document.getElementById("diaryList").innerHTML = "<p>Your baby currently has no diary entry.</p>";
} else {
var appendedText = '';
$.each(data, function(){
var diaryID = this.diary_id;
var dateAdded = this.date;
appendedText = appendedText + '<p><button type="button" class="diaries" value ="' + diaryID + '">' + dateAdded + '</button></p>';
})
document.getElementById("diaryList").innerHTML = appendedText;
}
});
$('div').on('click', '.diaries', function(event){
alert("Hi");
}) ;
});
</script>
<div id="diaryList"></div>
check your code is after document ready
$(document).ready(function(){ //your code here });
and use
$('button.diaries').on(click , function(){})
instead of .click

Check Checkbox in jquery

This is my current code. What I am trying to accomplish is as follows.
If json[i].enabled is true, I need to check the corresponding checkbox. If not, leave it empty.
function createTable(json) {
var element = "";
var i;
for (i = 0; i < json.length; i++) {
element = element
+ '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
}
//Had forgotten to add this before.
element = element + '</tbody>';
$('#dataTable > tbody').remove();
$("#dataTable").append(element);
}
I tried it by including the following if condition but it fails.
if(json[i].enabled== "TRUE"){
$('checkbox').prop('checked', true);
}
So, how do I go about doing this? How do I access that particular checkbox in the loop?
Thanks!
Using string concatenation and a ternary operator:
'<tr><td><input type="checkbox"' + ( json[i].enabled== "TRUE" ? ' checked' : '' ) + '/></td><td>'
$('input[type="checkbox"]').prop('checked', true);
complete example:
var $table=jQuery('<table></table>');
for (i = 0; i < json.length; i++) {
var $tr=jQuery(
'<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>');
if(json[i].enabled== "TRUE"){
$tr.find('input["checkbox"]').prop('checked', true);
}
$table.append($tr);
}
$jQuery('body').append($table);
The checbox element has not been created yet in the DOM. So you have to put the html first. Then use
input[type="checkbox"]
to match an actual checkbox element. And at last, you might want to get the last checkbox only (in the last row of your table) with this selector :
mytable tbody tr:last input[type="checkbox"]
So you have the following code :
function createTable(json) {
var i;
for (i = 0; i < json.length; i++) {
// construct the html
element = '<tr><td><input type= "checkbox"/></td><td>'
+ json[i].a_id + '</td><td>' + json[i].name + '</td><td>'+ json[i].enabled
+ '</td></tr>';
// put the html in the page
$('#mytable tbody').append(element);
if(json[i].enabled== "TRUE"){
// get the last inserted line in the table and check the checkbox
$('#mytable tbody tr:last input[type="checkbox"]').prop('checked', true);
}
}
}
Try this:
$('input[type="checkbox"]:eq(i)').prop('checked', true);

Button click not fire after remove element

I have create a div like this
<div id="hidden">
<img src="photos/Close-2-icon.png" width="16" height="16">
<input id="add" value="Add feild" type="button" >
<input type='button' id='h_div_ok' value="check !" />
<div id="inside_display" >
</div>
<input type="button" value="Insert" id="btninser" >
</div>
and when click the add button it will create a table. This is the jquery for
that.$("#add").click(function() {
i++;
var input = jQuery('<tr><td><input type=\"text\" id=\"input_'+i+'\"></td><td><textarea id=\"txtar_'+i+'\"></textarea></td><td><input type=\"button\" id=\"remove_'+i+'\" value=\"Remove\" /></td></tr>');
if(i == 1){
jQuery('#hidden').append('<table>');
jQuery('#hidden table').append(input);
jQuery('#hidden table').append('</table>');
}else{
jQuery('#hidden table tr:last').after(input);
}
$("#remove_" + i).click(function(){
if(i == 1){
$(this).closest("table").remove();
}else{
$(this).closest("tr").remove();
}
});
i is a global variable. Then after click the btninser button it will generate a string of the dynamically created table code.
$('#btninser').click(function(){
$('#'+id).text(getval());
$("#hidden table").remove();
});
function getval(){
var htmlString = '<table>';
var j;
for(j=1; j<=i; j++){
if($('#input_'+j).length === 0){
}else{
var itval = $('#input_'+j).val();
var taval = $('#txtar_'+j).val();
htmlString =htmlString + ('<tr><td>'+itval+'</td><td>'+taval+'</td></tr>');
}
}
htmlString =htmlString + ('</table>');
return htmlString;
}
in this case id also a global variable and it is just a id of a textare. after that if i click add button again that event not firing. How can i solve this ?
Here you should go with "i--" it make ur "i" count correct ,same as u done with i++.
also need to do this
$('#remove_'+i).click(function () {
i--;
});
Your code
$(document).ready(function () {
$("#add").click(function () {
i++;
var input = jQuery('<tr><td><input type=\"text\" id=\"input_' + i + '\"></td><td><textarea id=\"txtar_' + i + '\"></textarea></td><td><input type=\"button\" id=\"remove_' + i + '\" value=\"Remove\" /></td></tr>');
if (i == 1) {
jQuery('#hidden').append('<table>');
jQuery('#hidden table').append(input);
jQuery('#hidden table').append('</table>');
} else {
jQuery('#hidden table tr:last').after(input);
}
$("#remove_" + i).click(function () {
if (i == 1) {
$(this).closest("table").remove();
} else {
$(this).closest("tr").remove();
}
});
$('#btninser').click(function () {
$('#' + id).text(getval());
$("#hidden table").remove();
})
**$('#remove_'+i).click(function () {
i--;
});**
});
});
function getval() {
alert("getval");
var htmlString = '<table>';
var j;
for (j = 1; j <= i; j++) {
if ($('#input_' + j).length === 0) {
} else {
var itval = $('#input_' + j).val();
var taval = $('#txtar_' + j).val();
htmlString = htmlString + ('<tr><td>' + itval + '</td><td>' + taval + '</td></tr>');
}
}
htmlString = htmlString + ('</table>');
return htmlString;
}
I think you need to reset i variable so your table will be redrawn again when pressing add button (if (i == 1))
$('#btninser').click(function() {
$('#' + id).text(getval());
$("#hidden table").remove();
i = 0; //here!
});
if your 2nd code block is exactly how you have it in your code, then your #add event handler is missing its end close brackets. Also, Im not sure what you have that doing in front of the jquery selector..
that.$("#add").click(function() {
i++;
// .......
}else{
$(this).closest("tr").remove();
}
});
assuming your 2nd event handler is intended to be nested, it should be..
$("#add").click(function() {
i++;
// .......
}else{
$(this).closest("tr").remove();
}
});
});

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

Categories

Resources