pheromix
pheromix

Reputation: 19317

jQuery code does not work after resetting a div's content twice

There is a div element :

...
<div id="liste_secteurs"></div>
...
<script type="text/javascript">
$(document).ready(function() {
     rechercheSecteursEtProduits(0); // setting the div's content 
     $('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
        if ($(':checkbox[id^="prod_"]:checked').length > 0) {
            var msg = "Do you want to remove these records ?";
            if (confirm(msg)) {
                $(':checkbox[id^="prod_"]:checked').each(function(){
                    var type = "",id="";
                    if($(this).val() == "") {   //  delete secteur
                        type = "secteur";
                        var tabIdx = $(this).attr("id").substr(5);
                        id = $("#secteur_"+tabIdx).val();
                    } else {                    //  delete produit
                        type = "produit";
                        id = $(this).val();
                    }
                    $.ajax({
                        data: "type="+type+"&id="+id,
                        type: "POST",
                        url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                        async: false
                    });
                });
                rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
            }
        }
    });
});

function rechercheSecteursEtProduits(pn){

    var user = "<?php echo $_SESSION[CODE_USER]; ?>";
    var html = $.ajax({
        data: "id_user="+user,
        type: "POST",
        url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
        async: false
    }).responseText;

    $('#liste_secteurs').html(html); // this is the div element

}

</script>

Code of ListerProduitsUserParSecteursAjax.php :

<?php
... // getting database data
?>
<p>Total : <?php echo $nr; ?></p>
<div><a href="service.php?action=ServiceAjouterSecteurProduit"><img src="<?php echo HTTP_ICON.'plus.png'; ?>" /></a></div>
<?php echo $paginationDisplay; ?>
<table id="table" class="data display "  >
  <thead style="background-color:#CCC">
    <tr>
      <th><?php echo _getText("service.produit.form.secteur_activite");?></th>
      <th><?php echo _getText("service.produit.form.titre");?></th>
      <th></th>
      <th><?php if($data["secteur"]["cnt"] > 0){ ?><input type="checkbox" id="check_all"><?php }?></th>
    </tr>
  </thead>
  <tbody style="background-color:#FFF">
    <?php

    if($data["secteur"]["cnt"] > 0){
        for($i=0;$i<$data["secteur"]["cnt"];$i++){?>
    <tr class="odd gradeX">
      <td><?php echo $data["secteur"][$i]["secta_lib_fr"]  ?></td>
      <td><?php echo $data["secteur"][$i]["produit_lib"]  ?></td>
      <td align="center" style="vertical-align:middle"><a href="service.php?action=ServiceModifierSecteurProduit&s=<?php echo $data['secteur'][$i]['id_user_secteur']; ?>&p=<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><img src="<?php echo HTTP_ICON.'edit.png'; ?>" alt="<?php echo _getText('main.btn.modifier'); ?>" style="height:10px;width:10px;" /></a></td>
      <td align="center" style="vertical-align:middle"><input type="checkbox" id="prod_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_produit']; ?>"><input type="hidden" id="secteur_<?php echo $i; ?>" value="<?php echo $data['secteur'][$i]['id_user_secteur']; ?>"></td>
    </tr>
    <?php } ?>
    <?php 
    }
     else{
     ?>
    <tr class="odd gradeX">
      <td colspan="4" align="center"><b><?php echo _getText('main.liste.no_data'); ?></b></td>
    </tr>
    <?php }?>
  </tbody>
</table>
<?php if($data["secteur"]["cnt"] > 0){ ?>
<div align="right"><input name="btnSupprimer" id="btnSupprimer" type="button" value="<?php echo _getText("main.btn.delete"); ?>"   class="btn btn-blue"/></div>
<?php } ?>
<?php echo $paginationDisplay; ?>

When the page loads for the first time then the delete button works fine : the selected rows are deleted , and the list reappears accordingly to new database data. But later when I want to delete other rows then the alert does not show when I check some checkboxes and clicking the delete button !

So what is wrong in my approach ?

Upvotes: 0

Views: 114

Answers (4)

pheromix
pheromix

Reputation: 19317

As from Caveman's answer I made some updates :

function rechercheSecteursEtProduits(pn) {

    var user = "<?php echo $_SESSION[CODE_USER]; ?>";
    var html = $.ajax({
        data: "id_usermer="+user,
        type: "POST",
        url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
        async: false
    }).responseText;

    $('#liste_secteurs').html(html);
    $('#btnSupprimer').on('click',function(){
        if ($(':checkbox[id^="prod_"]:checked').length > 0) {
            if (confirm("Do you want to remove these records ?")) {
                $(':checkbox[id^="prod_"]:checked').each(function(){
                    var type = "",id="";
                    if($(this).val() == "") {   //  delete secteur
                        type = "secteur";
                        var tabIdx = $(this).attr("id").substr(5);
                        id = $("#secteur_"+tabIdx).val();
                    } else {                    //  delete produit
                        type = "produit";
                        id = $(this).val();
                    }
                    $.ajax({
                        data: "type="+type+"&id="+id,
                        type: "POST",
                        url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                        async: false
                    });
                });
                rechercheSecteursEtProduits(0);
            }
        }
    });

}

And it works !

Upvotes: 0

Dylan Reimerink
Dylan Reimerink

Reputation: 7948

From what I am reading you are having problems with the row that are added from the database. What could be the problem is when you execute this peace of code:

$('#btnSupprimer').click(function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"

When you call the $.click() function you add a event to all the existing DOM object that have a id of 'btnSupprimer', however this doesn't update if you add a new DOM object. So what you should do is call this function every time you add a new row. you would get something like this:

   function rechercheSecteursEtProduits(pn){

        var user = "<?php echo $_SESSION[CODE_USER]; ?>";
        var html = $.ajax({
            data: "id_user="+user,
            type: "POST",
            url:  "<?php echo HTTP_AJAX ?>service/ListerProduitsUserParSecteursAjax.php?pn=" + pn,
            async: false
        }).responseText;

        $('#liste_secteurs').html(html);
        $('#btnSupprimer').click(addClickHandler()); // this is the div element

    }


function addClickHandler(){
        if ($(':checkbox[id^="prod_"]:checked').length > 0) {
            var msg = "Do you want to remove these records ?";
            if (confirm(msg)) {
                $(':checkbox[id^="prod_"]:checked').each(function(){
                    var type = "",id="";
                    if($(this).val() == "") {   //  delete secteur
                        type = "secteur";
                        var tabIdx = $(this).attr("id").substr(5);
                        id = $("#secteur_"+tabIdx).val();
                    } else {                    //  delete produit
                        type = "produit";
                        id = $(this).val();
                    }
                    $.ajax({
                        data: "type="+type+"&id="+id,
                        type: "POST",
                        url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                        async: false
                    });
                });
                rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
            }
        }
    }

I hope it helps

Upvotes: 1

OneScrewLoose
OneScrewLoose

Reputation: 143

Use the dynamic jquery selector instead of the regular 'click' event

$('#liste_secteurs').on('click', '#btnSupprimer', function() {});

// $("container").on("event", "button", function() {});

Upvotes: 0

Ramzan Zafar
Ramzan Zafar

Reputation: 1600

Try using on instead of click as below

$('#btnSupprimer').on("click","#liste_secteurs",function() { // btnSupprimer = button generated from an ajax called inside previous function "rechercheSecteursEtProduits"
        if ($(':checkbox[id^="prod_"]:checked').length > 0) {
            var msg = "Do you want to remove these records ?";
            if (confirm(msg)) {
                $(':checkbox[id^="prod_"]:checked').each(function(){
                    var type = "",id="";
                    if($(this).val() == "") {   //  delete secteur
                        type = "secteur";
                        var tabIdx = $(this).attr("id").substr(5);
                        id = $("#secteur_"+tabIdx).val();
                    } else {                    //  delete produit
                        type = "produit";
                        id = $(this).val();
                    }
                    $.ajax({
                        data: "type="+type+"&id="+id,
                        type: "POST",
                        url:  "<?php echo HTTP_AJAX ?>service/SupprimerSecteursProduitsUserAjax.php", // deleting database row
                        async: false
                    });
                });
                rechercheSecteursEtProduits(0); // this causes the bug : the "delete" button does not work anymore after this code is called !
            }
        }
    });

Upvotes: 0

Related Questions