1

I have information that comes out of a database and gets put into a list with a checkbox by each element. This is how it is currently done:

  function subjects(){
    $.ajax({
    url: "lib/search/search.subject.php",
    async: "false",
    success: function(response){
    alert(response);
            var responseArray = response.split(',');    
            for(var x=0;x<responseArray.length;x++){
            $("#subjects").append("<br />");
            $("#subjects").append(responseArray[x]);
            $("#subjects").append("<input type='checkbox' />");
            }           
        }
    });
}

it works fine, but I need a way to pick up on if a checkbox is clicked, and if it is clicked then display which one was clicked, or if multiple ones are clicked.

I can't seem to find a way to pick up on the checkboxs at all.

the response variable is "math,science,technology,engineering"

3
  • Look into jQuery's .on() function. Commented Dec 19, 2012 at 20:38
  • Can you specify what's return in your response ? Commented Dec 19, 2012 at 20:43
  • response = math,science,technology,engineering Commented Dec 19, 2012 at 20:44

4 Answers 4

3

Because you are populating the Checkboxes Dynamically you need to Delegate the event

$("#subjects").on("click", "input[type='checkbox']", function() {
    if( $(this).is(":checked") ) {
       alert('Checkbox checked')
    }
});

To better capture the data it is better if you encase the corresponding data into a span , so that it can be easier to search..

 $("#subjects").append('<span>'+responseArray[x] + '</span>');

$("#subjects").on("click", "input[type='checkbox']", function() {
        var $this = $(this);
        if( $this.is(":checked") ) {
            var data = $this.prev('span').html();
            alert('Current checkbox is : '+ data ) 
        }
    });
Sign up to request clarification or add additional context in comments.

Comments

0

It would be best to give your dynamically injected checkboxes a class to target them better, but based on your code try:

$("#subjects").on("click", "input", function() {
    if( $(this).is(":checked") ) {
    // do something
    }
});

Since your input elements are added dynamically, you need to use jQuery's .on() function to bind the click event to them. In your case you need to use .on() to bind to an element that exist in the DOM when the script is loaded. In your case, the element with the ID #subjects.

This note from the docs is mainly for machineghost who downvoted my answer for no apparent reason:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page.

Comments

0
$('#subjects input[type=checkbox]').on('click',function(){
    alert($(this).prop('checked'));
});

or the change event: in case someone uses a keyboard

$('#subjects input[type=checkbox]').on('change',function(){
    alert($(this).prop('checked'));
});

simple fiddle example:http://jsfiddle.net/Dr8k8/

to get the array example use the index of the inputs

alert($(this).prop('checked') +'is'+ $(this).parent().find('input[type=checkbox]').index(this)+ responseArray[$(this).parent().find('input[type=checkbox]').index(this) ]);

simplified example: http://jsfiddle.net/Dr8k8/1/

EDIT: Just for an example, you could put the results in an array of all checked boxes and do somthing with that:

$('#subjects>input[type=checkbox]').on('change', function() {
    var checklist = [];
    $(this).parent().find('input[type=checkbox]').each(function() {
        $(this).css('background-color', "lime");
        var myindex = $(this).parent().find('input[type=checkbox]').index(this);
        if ($(this).prop('checked') == true) {
            checklist[myindex] = responseArray[myindex];
        }
    });
    $('#currentlyChecked').text(checklist);
});

EDIT2:

I thought about this a bit and you can improve it by using .data() and query that or store it based on an event (my button called out by its id of "whatschecked")

var responseArray = ['math', 'science', 'technology', 'engineering'];// just for an example
var myList = '#subjects>input[type=checkbox]';//to reuse
for (var x = 0; x < responseArray.length; x++) {
    // here we insert it all so we do not hit the DOM so many times
    var iam = "<br />" + responseArray[x] + "<input type='checkbox' />";
    $("#subjects").append(iam);
    $(myList).last().data('subject', responseArray[x]);// add the data
}
var checklist = [];// holds most recent list set by change event
$(myList).on('change', function() {
    checklist = [];
    $(myList).each(function() {
        var myindex = $(this).parent().find('input[type=checkbox]').index(this);
        if ($(this).prop('checked') == true) {
            checklist.push($(this).data('subject'));
            alert('This one is checked:' + $(this).data('subject'));
        }
    });
});
// query the list we stored, but could query the checked list data() as well, see the .each() in the event handler for that example
$("#whatschecked").click(function() {
    var numberChecked = checklist.length;
    var x = 0;
    for (x = 0; x < numberChecked; x++) {
        alert("Number " + x + " is " + checklist[x] + " of " + numberChecked);
    }
});

live example of last one: http://jsfiddle.net/Dr8k8/5/

Comments

-1

The general pattern to do something when a checkbox input is clicked is:

$('input[type=checkbox]').click(function() {
    // Do something
})

The general pattern to check whether a checkbox input is checked or not is:

var isItChecked = $('input[type=checkbox]').is(':checked');

In your particular case you'd probably want to do something like:

$('#subjects input[type=checkbox]').click(function() {

to limit the checkboxes involved to the ones inside your #subjects element.

6 Comments

This won't work if the input fields don't exist when the page loads.
Umm, obviously, but that had nothing to do with the question. The author asked " I need a way to pick up on if a checkbox is clicked, and if it is clicked then display which one was clicked, or if multiple ones are clicked." I provided both a way of detecting clicks and a way of checked for clicked (checked) status.
However you code won't work based on the OP's code. Obviously.
What are you talking about? My code is just generic jQuery code; it is 100% applicable to the OP.
You should probably brush up on how dynamically added elements need to be bound to events when using jQuery.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.