Skip to content
Advertisement

Problem in code with jquery, php and html

    <script>
$(document).ready(function () {
    $("button").click(function(){
        $("button").parent().append('<select name="produto_tipo" >
            <?php 
            $sql3 = "SELECT idproduto, produto_nome,produto_preço FROM produtos";
            $stmt3 =$pdo->prepare($sql3);
            $stmt3->execute();
            while($row2=$stmt3->fetch(PDO::FETCH_BOTH)):;
            ?>
            <option value="<?php echo $row2[0];?>"><?php echo $row2[1];?><?php echo $row2[2]."$"; ?></option>

            <?php endwhile;?>
        </select>');
    });
});

</script>
<button class='w3-bar-item w3-button'>Inserir Produto</button>

I have 2 errors in this code;

here <select name=produto_tipo > on > is red

and here </select>'); on ; same it is red

Where am I failing?

Advertisement

Answer

<?php
$sql3  = "SELECT idproduto, produto_nome,produto_preço FROM produtos";
$stmt3 = $pdo->prepare($sql3);
$stmt3->execute();
$options = '';
while ($row2 = $stmt3->fetch(PDO::FETCH_BOTH)) {
    $options .= "<option value="{$row2[0]}">{$row2[1]}{$row2[2]}$</option>";
}
?>
<script>
    $(document).ready(function () {
        $("button").click(function () {
            $("button").parent().append('<select name="produto_tipo"><?= $options ?></select>');
        });
    });
</script>

I executed the script and the result was:

<script>
    $(document).ready(function () {
        $("button").click(function () {
            $("button").parent().append('<select name="produto_tipo"><option value="A">01$</option><option value="B">23$</option><option value="C">45$</option></select>');
        });
    });
</script>
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement