modify an input and update

Asked

Viewed 176 times

0

php

Could someone give me tips on implementing a part? i had printed an input of type text inside the while loop: "<td><input type='text' value='".$valor['url_video']."' style='width: 400px;' id='url-video'></td>". , within this input is printed the value url_video, by clicking on the btn update, I have it update the selected input field var string = $('#url-video').val(); the problem is that it only updates the first column url_video, is giving trouble in the other (is made only a copy of this first for other fields). I think the problem is when I input my input as id='url-video', Right? You can give me tips?

    echo "<table class='table'>".
        "<thead>".
             "<tr>".
                "<td>ID</td>".
                "<td>url_video</td>".
             "</tr>".
        "</thead><tbody>";
while($valor = mysqli_fetch_array($resultado)){
    echo "<tr>".
            "<td>".$valor['ID']."</td>".
            "<td><input type='text' value='".$valor['url_video']."'  style='width: 400px;' id='url-video'></td>".
            "<td><input type='button' value='Update' class='btn-update' data-id='".$valor['ID']."' >"."</td>".
         "</tr>";
}
echo "</tbody></table>";

ajax

$(document).ready(function(){

    $('.btn-update').click(function(){
        var id = $('.btn-update').data('id');
        var string = $('#url_video').val();

        $.ajax({
            url: "tabelaUpdate.php",
            data: { 'idDeUpdate' : id,
                    'url_video' : string
                  },
            type: "POST",
            cache: false,
            success: function(response){
                //alert("ok"+response);
                $('#result').html(response); //serve para ver a array foi inserida mesmo
            }
        })
    });
});

1 answer

2


Use id this way inside a loop is unviable. Ids are UNIQUE, if you have two equal on the same page the JS gives pall.

Solution (Added Video ID to Input ID):

while($valor = mysqli_fetch_array($resultado)){
    echo "<tr>".
            "<td>".$valor['ID']."</td>".
            "<td><input type='text' value='".$valor['url_video']."'  style='width: 400px;' id='url-video-".$valor['ID']."'></td>".
            "<td><input type='button' value='Update' class='btn-update' data-id='".$valor['ID']."' >"."</td>".
         "</tr>";
}

And the JS recovers the right field by using the button ID:

$('.btn-update').click(function(){
    var id = $('.btn-update').data('id');
    var string = $('#url_video-'+id).val();

    $.ajax({
        url: "tabelaUpdate.php",
        data: { 'idDeUpdate' : id,
                'url_video' : string
              },
        type: "POST",
        cache: false,
        success: function(response){
            //alert("ok"+response);
            $('#result').html(response); //serve para ver a array foi inserida mesmo
        }
    })
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.