mardi 28 mars 2023

How do I get the current checkbox value on click into ajax when thousands of checkboxes are possible?

I need to get the value of a checkbox during an onclick event into ajax so that I can run some php code based on the checkbox value. When I have a simple webpage with a single checkbox

<input type='checkbox' class='fav' id='chk' value='Something_123' onclick='AddRemoveFav()'>

I can easily get the value into PHP via ajax using

<script type='text/javascript>
    function AddRemoveFav(){
        if ($('chk').is(':checked')){
            $.ajax({
                type: 'POST',
                url: 'addRemoveFav.php',
                data: {checked_box : $('chk').val()),
                success: function(data){
                    $('#message').html(data);
                }
             });
          }

Unfortunately there may be thousands of checkboxes that are created in a php echo statement (each with a unique id such as id='chk1', id='chk2', etc) so now I don't know how to get the event to fire on only the checkbox that was selected and not on other checkboxes that were previously selected. I've spent the last few hours on SO trying different things but so far nothing has worked out. My thought is that I need to do something like onclick='AddRemoveFav(this)' and then use that in the ajax below but that is where I am stuck. Any help is greatly appreciated.




Aucun commentaire:

Enregistrer un commentaire