0

I need create a table, in the column the size and in the row the quantity for every product, I create a query where put in array the different result to have column and row and after I create a table.. I need to update every time there anybody do a change

while($xx < count($testa))
    {
        $testaecho .= "<th>".$testa[$xx]."</th>";
        $corpoecho .= "<td style=' max-width: 20px;'>";
        $corpoecho .= "<form name='changeqta' method='post' action=''>";
        $corpoecho .= "<input type='number' maxlength='3' id='mod' value='".$corpo[$xx]."'>";
        $corpoecho .= "<input type='hidden' id='ctgr' value='".$idriga[$xx]."'>";
        $corpoecho .= "</form>";
        $corpoecho .= "</td>";
        $xx++;
    }

   echo "<tr>".$testaecho."</tr>";
   echo "<tr>".$corpoecho."</tr>";

and in the jquery

<script>
$(document).ready(function(){
    $('#mod').on('change', function(){
        var name=$("#mod").val();
        var ctgr=$("#ctgr").val();
        $.ajax({
            url:'update.php',
            method:'POST',
            data:{
                name:name,
                ctgr:ctgr
            },
            success:function(response){
                alert(response);
            }
        });
    });
});

the problem is only the first input do the change, if i change all other input, the firs product or the other product not update... is the same that the second "mod" is not do the submit

why?

ADyson
  • 57,178
  • 14
  • 51
  • 63
  • 11
    ... _[sigh]_. Here we go again: IDs in a HTML document must be unique (just like any ID, in any situation is supposed to be unique - that's the whole point of them!). Your `while` loop is creating lots of `id="mod"` fields. So `$('#mod')` tries to select by ID, and finds lots of items with the same ID, which isn't allowed. Therefore it just selects the first one, and ignores the others. To catch lots of elements with an event handler, you can (for example) use a class instead, e.g. ` – ADyson Mar 03 '23 at 12:05
  • 2
    More info: https://api.jquery.com/id-selector/, https://api.jquery.com/class-selector/ – ADyson Mar 03 '23 at 12:05
  • 1
    Does this answer your question? [jQuery ID selector works only for the first element](https://stackoverflow.com/questions/11114622/jquery-id-selector-works-only-for-the-first-element) – Don't Panic Mar 03 '23 at 13:11

1 Answers1

1

Since duplicate id is not possible try using a class. And try using attribute instead another hidden input. For example,

$corpoecho .= "<input type='number' maxlength='3' class='mod' data-mod='".$idriga[$xx]."' value='".$corpo[$xx]."'>";

check on data-mod='".$idriga[$xx]."'

Now access in jquery like this,

$('.mod').on('change', function(){
        var name = $(this).val(); // Get the value of changed item
        var ctgr = $(this).attr('data-mod'); // get arrtibute value
 ....
}
vimuth
  • 5,064
  • 33
  • 79
  • 116