b0w3rb0w3r
b0w3rb0w3r

Reputation: 937

Getting a Dynamically generated ID

I have a checkbox where the values are dynamically populated from the data on my database. I would like to perform further queries based on the clicked checkbox, however I cant seem to retrieve the ID whenever I click on any of the checkboxes. I do not want to use a submit button. How can this be achieved??

My code.

function getDBlist() {
            global $link;
            $qry = ("SHOW DATABASES");
            $res = mysqli_query ( $link, $qry );
            while ( $row = mysqli_fetch_assoc ( $res ) ) {
                echo '<input type="checkbox" name="db" id="' . $row ['Database'] . '"   value="' . $row ['Database'] . '" />';
                echo $row ['Database'];
            }
        }
        getDBlist (); 

My Script

$(document).on("change","checkbox", function() {
    var val = $(this).val();
    var id = this.id;
    alert(val, id);
});

When I click on any of the checkboxes I don't get an alert with either the value or the ID. What am I doing wrong here? Could it be because of my dynamically generated ID?

Upvotes: 0

Views: 1253

Answers (4)

Bhushan Kawadkar
Bhushan Kawadkar

Reputation: 28513

To bind change event to the dynamically generated checkboxes you need to delegate change event like below

$(document).on("change",".checkbox", function() {
    var val = $(this).val();
    var id = this.id;
    alert(val, id);
});

Above code will work for both existing and dynamically created checkboxes. Here document object will delgate change event to checkboxes with class="checkbox"

Also as mentioned by @Ghost, you need to add class to dynamically generated checkboxes like below

echo '<input type="checkbox" 
             name="db" id="' . $row ['Database'] . '"   
             value="' . $row ['Database'] . '" 
             class="checkbox"/>';

More Information for .on()

Upvotes: 2

SimarjeetSingh Panghlia
SimarjeetSingh Panghlia

Reputation: 2200

Try this

$("body").on("change",".checkbox", function() {
    var val = $(this).val();
    var id = $(this).attr("id");
    alert(val, id);
});

Upvotes: 0

Steve
Steve

Reputation: 20469

Your jquery selector is looking for an element with the css class `checkbox', either add this class to your html:

echo '<input type="checkbox" class="checkbox"...';

Or remove the period in the selector, to target all checkbox elements:

$("checkbox").on("change", function() {
    var val = $(this).val();
    var id = this.id;
    alert(val, id);
});

Upvotes: 0

Kevin
Kevin

Reputation: 41885

Looking at your echo statement rendering the markup, you haven't designated class="checkbox" at all:

echo '<input type="checkbox" name="db" id="' . $row ['Database'] . '"   value="' . $row ['Database'] . '" />';

Since you haven't added it, pointing to $(".checkbox") won't work. You need to add them in the echo.

Upvotes: 2

Related Questions