How to work with dynamic form in jquery?

Asked

Viewed 253 times

0

I wonder how I can work in a simple way with this dynamic form , type the categories comes from the database via jquery and ajax and appears on the screen as a form for the user to select your request . As you can see in my code only the table input has name"" the others not because they appear dynamically . But my doubt over the course of the week was that I could not show or even send to mysql what is requested by the user. How could by the same show on another screen what is selects in the form .

My form

 <div class="container">

           <h1 class="restaurant-title">Peixaria</h1>


          <div id="menu-panel" class="col-sm-12 paddingselect">

                  <?php
                     categoriaas();
                  ?>

          </div>


          <div id="menu-panel-2">




          </div>



          <div id="caja-panel">
            <div class="well">

            <form method="post" action="relatorio.php" id="formRel">
                <!-- left -->
                <div id="theproducts" class="col-sm-5">
                </div>
                <!-- left -->
                <span>Mesa:</span>
            <input type="text" name="mesa"value="">
                <input type="text" id="theinputsum">

                <!-- right -->
                <div id="thetotal" class="col-sm-7">
                   <h1 id="total"></h1>

                   <button  class="btn btn-lg btn-success btn-block"><i  type="submit" class="fa fa-shopping-cart" aria-hidden="true"></i> Finalizar Pedido</button>
                </div>
                <!-- right -->
</form>

            </div>
          </div>



     </div>
     <!-- container -->

<script>
$('#formRel').submit(function(event){

        event.preventDefault();
        var formDados = new FormData($(this)[0]);
$.ajax({
  method: "POST",
  url: "relatorio.php",
  data: $("#formRel").serialize(),
  dataType : "html"
});
};
 </script>

    <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
    <script src="js/jquery.min.js"></script>
    <!-- Include all compiled plugins (below), or include individual files as needed -->
    <script src="js/bootstrap.min.js"></script>
    <!-- Restaurant -->
    <script src="js/restaurant.js"></script>

this is the part that brings the categories of mysql to the screen .

<?php

require_once 'conexion.class.php';




function categoriaas(){

   $conexion = Conexion::singleton_conexion();

   $SQL = 'SELECT * FROM categorias';
   $stn = $conexion -> prepare($SQL);
   $stn -> execute();
   $results = $stn -> fetchAll();
   if (empty($SQL)){
   }else{

       foreach ($results as $key){

           echo '
                <div class="col-md-4 col-sm-4">
                <button data-categoria="'.$key['id'].'" class="restaurantcatbtn btn btn-default btn-lg btn-block"><i class="fa fa-chevron-right" aria-hidden="true"></i> '.$key['nombre'].'</button>
                </div>
           ';

       }

   }

}



function getproductos($productos){

   $conexion = Conexion::singleton_conexion();

   $SQL = 'SELECT * FROM productos WHERE categoria = :categoria';
   $stn = $conexion -> prepare($SQL);
   $stn -> bindParam(':categoria', $productos, PDO::PARAM_INT);
   $stn -> execute();
   $results = $stn -> fetchAll();
   if (empty($SQL)){
   }else{

       foreach ($results as $key){

           echo '
                <div class="col-md-4 col-sm-4">
                <button id="theproductitem'.$key['id'].'" data-nombre="'.$key['nombre'].'"  data-precio="'.$key['precio'].'" class="btn btn-default btn-lg btn-block" onclick="agregarcaja('.$key['id'].')"><i class="fa fa-cutlery" aria-hidden="true"></i> '.$key['nombre'].' <p>($'.$key['precio'].')</p></button>
                </div>
           ';

       }

   }

}

the javascript code

$('.restaurantcatbtn').on('click', function(){

    var attrcat = $(this).attr('data-categoria');
    var datacat = 'categoria='+attrcat;

    $.ajax({

       type: 'POST',
       url: 'includes/processfunction.php',
       data: datacat,
       beforeSend: function(){
            $('#menu-panel-2').append('<div class="cssload-thecube"><div class="cssload-cube cssload-c1"></div><div class="cssload-cube cssload-c2"></div><div class="cssload-cube cssload-c4"></div><div class="cssload-cube cssload-c3"></div></div>');
       },
       success: function(data){
           $('#menu-panel-2').html(data);

       },
       error: function(){

       }

    });

});


function agregarcaja(producto){

       var addproducto = $('#theproductitem'+producto).attr('data-nombre');
       var dataprocutstock = $('#theproductitem'+producto).attr('data-stock');
       var dataprocutprecio = $('#theproductitem'+producto).attr('data-precio');
       var addproductodiv = $('#cajaitem'+producto);
       var theinputsum = $('#theinputsum');

       if ($(addproductodiv).length)
        {
            return;

        }else{

            if (theinputsum.val() == ''){

               theinputsum.val(dataprocutprecio);
               $('#total').text('Total a pagar: $'+dataprocutprecio);

            }else{

               var lastthevalue = theinputsum.val();
               var thenextvalue = parseFloat(lastthevalue) + parseFloat(dataprocutprecio);
               theinputsum.val(thenextvalue);
               $('#total').text('Total a pagar: $'+thenextvalue);

            }

            $('#theproducts').append('<span id="cajaitem'+producto+'" data-precio="'+dataprocutprecio+'" data-cantidad="1" class="btn btn-block btn-sm">'+addproducto+' [$'+dataprocutprecio+'] <p id="thepitemcantidad'+producto+'" class="pull-right cantidad-item-p">1</p> <button style="margin-left:4px;" onclick="cantidadProductoPlus('+producto+')" class="btn btn-xs btn-success pull-right"><i class="fa fa-plus-square" aria-hidden="true"></i></button> <button class="btn btn-xs btn-danger pull-right"><i class="fa fa-minus-square" onclick="cantidadProductoMinus('+producto+')" aria-hidden="true"></i></button> </span>'); 

       }  

}


function cantidadProductoMinus(producto){

      var cantidad = $('#cajaiteminput'+producto).val();
      var precio = $('#cajaitem'+producto).attr('data-precio');
      var cantidaditem = $('#cajaitem'+producto).attr('data-cantidad');
      var theinputsum = $('#theinputsum').val();
      var theinputsumelement = $('#theinputsum');


      if (cantidaditem == 1){

          var thedeleteitem = parseFloat(theinputsum) - parseFloat(precio);
          theinputsumelement.val(thedeleteitem);
          if (thedeleteitem == 0){
             $('#total').text('');
          }else{
             $('#total').text('Total a pagar: $'+thedeleteitem);
          }

          $('#cajaitem'+producto).remove();

      }else{

          var thefinalcantidad = parseInt(cantidaditem) - 1;
          var thedeleteitem = parseFloat(theinputsum) - parseFloat(precio);
          theinputsumelement.val(thedeleteitem);
          $('#thepitemcantidad'+producto).text(thefinalcantidad);
          $('#cajaitem'+producto).attr('data-cantidad', thefinalcantidad);
          var minusprice = parseFloat(theinputsum) - parseFloat(precio);
          $('#theinputsum').val(minusprice);
          $('#total').text('Total a pagar: $'+minusprice);



      }


}


function cantidadProductoPlus(producto){
        var cantidaditem = $('#cajaitem'+producto).attr('data-cantidad');
        var precio = $('#cajaitem'+producto).attr('data-precio');
        var theinputsum = $('#theinputsum').val();
        var sumprice = parseFloat(theinputsum) + parseFloat(precio);
        var thefinalcantidad = parseInt(cantidaditem) + 1;
        $('#thepitemcantidad'+producto).text(thefinalcantidad);
        $('#cajaitem'+producto).attr('data-cantidad', thefinalcantidad);
        $('#theinputsum').val(sumprice);
        $('#total').text('Total a pagar: $'+sumprice);
}

an image to illustrate my table .

inserir a descrição da imagem aqui

  • 1

    It is good to clarify that coming or not dynamically, does not imply in having or not properties, if you need just change the functions categoriaas and products.

  • The key to your problem is a javascript aggregation function, which you have not posted.

  • already put the javascript code @Rodrigosartorijarouche

No answers

Browser other questions tagged

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