1

I am trying to create a check box with some value and then display the values of selected check boxes separated by a comma.

I can create a checkbox but I am unable to display the values in a text box. Please help.

http://jsfiddle.net/0q0ns1ez/1/

function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB[0] = $(this).attr("id");
            }
        });
        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    
Sergio
  • 28,539
  • 11
  • 85
  • 132
XXDebugger
  • 1,581
  • 3
  • 26
  • 48

3 Answers3

0

You are overwriting CountSelectedCB[0].

Better try something like

var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
    $target.val(
        $checkboxes.map(function() {
            return this.checked ? this.id : null;
        }).get().join()
    );
});

var abc = [1, 2, 3];
var CountSelectedCB = new Array();
var s1 = document.getElementById('demo');
for (var option in abc) {
  if (abc.hasOwnProperty(option) && !document.getElementById('CheckBox' + abc[option])) {
    var pair = abc[option];
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = 'CheckBox' + pair;
    checkbox.name = pair;
    checkbox.value = pair;
    s1.appendChild(checkbox);

    var label = document.createElement('label')
    label.htmlFor = pair;
    label.appendChild(document.createTextNode(pair));
    s1.appendChild(label);
    s1.appendChild(document.createElement("br"));
  }
}
var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
  $target.val(
    $checkboxes.map(function() {
      return this.checked ? this.id : null;
    }).get().join()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="demo"></div>
<input type="text" name="selectedCB" />

Or like this:

var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
    $target.val(
        $checkboxes.filter(':checked').map(function() {
            return this.id;
        }).get().join()
    );
});

var abc = [1, 2, 3];
var CountSelectedCB = new Array();
var s1 = document.getElementById('demo');
for (var option in abc) {
  if (abc.hasOwnProperty(option) && !document.getElementById('CheckBox' + abc[option])) {
    var pair = abc[option];
    var checkbox = document.createElement("input");
    checkbox.type = "checkbox";
    checkbox.id = 'CheckBox' + pair;
    checkbox.name = pair;
    checkbox.value = pair;
    s1.appendChild(checkbox);

    var label = document.createElement('label')
    label.htmlFor = pair;
    label.appendChild(document.createTextNode(pair));
    s1.appendChild(label);
    s1.appendChild(document.createElement("br"));
  }
}
var $target = $('input[name=selectedCB]');
var $checkboxes = $("input[type=checkbox]").on('change', function() {
  $target.val(
    $checkboxes.filter(':checked').map(function() {
      return this.id;
    }).get().join()
  );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="demo"></div>
<input type="text" name="selectedCB" />
Oriol
  • 274,082
  • 63
  • 437
  • 513
0

There main issue with your approach is in this line:

CountSelectedCB[0] = $(this).attr("id");

The way you are using the array CountSelectedCB, you are always inserting the id of a check box at the first position (index 0) so you will always end up with one id no matter how many checkboxes are checked (or no ids) if no checkboxes are checked.

You should change the line above to:

CountSelectedCB.push($(this).attr("id"));

Also, since CountSelectedCB is in a higher scope then displayCheckbox function, it keeps it's values between calls to displayCheckbox so on each firing of the change event, you have to clear the array before adding the updated list of checked ids. Otherwise, your updated list of ids will get appended to previously stored list.

Here is how your code could look like (sample Fiddle):

function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];

        CountSelectedCB.length = 0;                       // clear selected cb count before adding the updated ones
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("id")); // add id to count selected cb
            }
        });

        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    

$(document).ready(displayCheckbox);

CountSelectedCB = [];

function displayCheckbox(){    
    $("input:checkbox").change(function() {          
        selectedCB = [];
        notSelectedCB = [];
        
        CountSelectedCB.length = 0; // clear selected cb count
        $("input:checkbox").each(function() {
            if ($(this).is(":checked")) {
                CountSelectedCB.push($(this).attr("id"));
            }
        });
        
        $('input[name=selectedCB]').val(CountSelectedCB); 
    });
}    
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb1">Checkbox #1
<input type="checkbox" id="cb2">Checkbox #2
<input type="checkbox" id="cb3">Checkbox #3
<hr />
<input name="selectedCB">

Here is another way of achieving this (sample Fiddle)

Essentially, you initially add a change listener to every check box (on document ready or some other event depending on your application logic) that will print all checked boxes.

var checkboxes = $("input:checkbox"); // save checkboxes into a variable so we don't waste time by looking them up each time

// add change listeners to checkboxes
$.each(checkboxes, function() {
  $(this).change(printChecked);
})

And you make a function to actually print ids of the checked boxes:

function printChecked() {
    var checkedIds = [];

    // for each checked checkbox, add it's id to the array of checked ids
    checkboxes.each(function() {   
        if($(this).is(':checked')) {
            checkedIds.push($(this).attr('id'));
        }
    });

    $('input[name=selectedCB]').val(checkedIds); 
}

$(document).ready(displayCheckbox);

function displayCheckbox() {    
   
    var checkboxes = $("input[type=checkbox]");
    var displayField = $('input[name=selectedCB]');

    $.each(checkboxes, function() {
      $(this).change(printChecked);
    })
    
    function printChecked() {
        var checkedIds = [];

        // for each checked checkbox, add it's id to the array of checked ids
        checkboxes.each(function() {   
            if($(this).is(':checked')) {
                checkedIds.push($(this).attr('id'));
            }
        });

        displayField.val(checkedIds); 
    }
}  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="cb1">Checkbox #1
<input type="checkbox" id="cb2">Checkbox #2
<input type="checkbox" id="cb3">Checkbox #3
<hr />
<input name="selectedCB">
Community
  • 1
  • 1
nem035
  • 34,790
  • 6
  • 87
  • 99
-1

You loop through all checkboxes and save the values in some String and then put it in textfield:

var string = "";
$('.checkButtonClass').each(function() {
     if($(this).is(':checked')) {
     string = string + $(this).val() +", ";
}
$("#idTextfield").html(string);
g_r4ni
  • 24
  • 5