How to sum a database record plus input with Jquery

Asked

Viewed 292 times

0

Hello how do I make this sum with Jquery:

have this table vehicles in the database with the review column of 500

inserir a descrição da imagem aqui

in the form when I choose the prefix MT-02 I want it to sum the input of the exchange horimetro (which will be typed) + revisao (that this record is in the database) and give the result in the input horimetro of the next exchange

inserir a descrição da imagem aqui

I have this sum plus is not picking up the database record (for reference) see where there is 500 in the code not wanted to put the number and yes to take the record that is in the database

<script type="text/javascript">
jQuery(document).ready(function(){
    jQuery('input').on('keyup',function(){
        if(jQuery(this).attr('name') === 'result'){
            return false;
        }

        var horimetroca = (jQuery('#horimetroca').val() == '' ? 0 : jQuery('#horimetroca').val());
        var proximatroca = (parseInt(horimetroca) + 500);
        jQuery('#proximatroca').val(proximatroca);
    });
});
</script>
  • Cara, I don’t know if I’m going to help you, but I would do a 'change' event in the vehicle field, which when I change make an ajax request (http://api.jquery.com/jquery.ajax/) passing the value of the field (e.g., MT-02) and in the back end would make a select using MT-02 in Where, and then return to the front, sum and display in the field.

  • Welcome Diogo Carvalho, for answers in your next questions please read this post https://answall.com/help/mcve. and this also https://pt.meta.stackoverflow.com/questions/5483/manual-de-como-n%C3%83o-ask-questions/

  • If any answer solves your problem be sure to mark it as accepted. See how marcar in this image https://i.stack.Imgur.com/evLUR.png and know why in this post https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta/1079#1079

1 answer

0


A simple example but you can understand how it works:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script language="javascript">
<!--
    $(document).ready(function () {
        //executa função no clique do botão class addMore
        $(".addMore").click(function(){
                //recupera os valores do formulário
                var prefixo = $("#prefixo").val();
                var horimetro = $("#horimetro").val();

                //prepara para enviar com o ajax para a buscaVeiculo.php
                var dataString = {"valorPrefixo":prefixo,"valorHorimetro":horimetro }

              $.ajax({
                url: 'buscaVeiculo.php',
                type: 'POST',
                data: dataString,
                success: function(data){
                //insere no input de id horimetroProxima o valor retornado    
                $("#horimetroProxima").val(data);
                },
                error: function(){
                //caso haja erro a frase abaixo será apresentada na div de id resultado    
                $("#resultado").html("Ouve um erro ao enviar sua URL");
                }
             });//ajax 

        });
    });
//-->
</script>

<div id="resultado"></div>

<select id="prefixo" size="1">
    <option>Veiculo</option>
    <option value="MT-02">MT-02</option>
    <option value="DF-02">DF-02</option>
    <option value="CM-01">CM-01</option>
</select>

<input id="horimetro" type="text"> <input id="horimetroProxima" type="text" readonly> <button class="addMore">add</button>

search engine.php

$Prefixo = $_POST['valorPrefixo'];
$Horimetro = $_POST['valorHorimetro'];

$conexao = new PDO('mysql:host=localhost;dbname=nome_DB',"USUARIO","SENHA");

    $sql = $conexao->prepare("SELECT revisao FROM veiculos where prefixo='$Prefixo'");
    $sql->execute();

    $linha = $sql->fetch(PDO::FETCH_ASSOC);

    $Revisao = $linha['revisao'];

    echo $Revisao+ $Horimetro;

Maybe you might like this solution

Script

    $(document).ready(function () {

        //$("#horimetro").blur(function(){
        $( ".qqum" ).on( "blur keyup change", function() {

            var prefixo = $("#prefixo").val();

            if (prefixo!="Veiculo"){

                var horimetro = $("#horimetro").val();
                var dataString = {"valorPrefixo":prefixo,"valorHorimetro":horimetro }

              $.ajax({
                url: 'buscaVeiculo.php',
                type: 'POST',
                data: dataString,
                success: function(data){
                    $("#horimetroProxima").val(data);
                },
                error: function(){
                    $("#resultados").html("Ouve um erro ao enviar sua URL");
                }
             });//ajax 
            }
        });
    });

HTML

<select class="qqum" id="prefixo" size="1">
    <option>Veiculo</option>
    <option value="MT-02">MT-02</option>
    <option value="DF-02">DF-02</option>
    <option value="CM-01">CM-01</option>
</select>

<input class="qqum" id="horimetro" type="text" placeholder="horimetro"> <input id="horimetroProxima" type="text" readonly>

As shown in Online Notpad of the AP comment

there must be various changes due to classes e ids different:

$( "#idVeiculo,#horimetroca" ).on( "blur keyup change", function() {                    
var prefixo = $("#idVeiculo").val();
if (prefixo!="Selecione"){
var horimetro = $("#horimetroca").val();
.............
.............
success: function(data){
   $("#proximatroca").val(data);

Code in full

<?php

$conexao = new PDO ....

$resultipo = $conexao->prepare("SELECT * FROM veiculos");
$resultipo->execute();
$resultados = $resultipo->fetchAll(PDO::FETCH_ASSOC);

?>

<div class="col-md-3">
          <div class="form-group">
            <b><label class="col-form-label" for="inputDefault">Veiculo</label></b>
              <select name="idVeiculo" class="form-control select2" id="idVeiculo" style="width:100%;" >
              <option value="" selected>Selecione</option>
      <?php
        foreach($resultados as $results):
      ?>
              <option value="<?php echo $results['prefixo'] ?>"><?php echo $results['prefixo']; ?></option>
      <?php
        endforeach;
      ?>
               </select>
          </div>
        </div>

        <div class="col-md-3">
          <div class="form-group">
            <b><label class="col-form-label" for="inputDefault">Data da Troca</label></b>
               <input type="date" name="datatroca"  value="<?php echo date('Y-m-d');?>" class="form-control"  id="datatroca" />
          </div>
        </div>

            <div class="col-md-3">
              <div class="form-group">
                <b><label class="col-form-label" for="inputDefault">Km da Troca</label></b>
                <input class="form-control" name="kmtroca" id="kmtroca" type="text">
              </div>
            </div>

            <!-- Soma da Proxima Troca em Ajax-->

            <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

                <script language="javascript">
                <!--
                    $(document).ready(function () {

                        $( "#idVeiculo,#horimetroca" ).on( "blur keyup change", function() {

                            var prefixo = $("#idVeiculo").val();

                            if (prefixo!="Selecione"){

                                var horimetro = $("#horimetroca").val();
                                var dataString = {"valorPrefixo":prefixo,"valorHorimetro":horimetro }

                              $.ajax({
                                url: 'buscaVeiculo.php',
                                type: 'POST',
                                data: dataString,
                                success: function(data){
                                    $("#proximatroca").val(data);
                                },
                                error: function(){
                                    $("#resultados").html("Ouve um erro ao enviar sua URL");
                                }
                             });//ajax 
                            }
                        });

                    });
                //-->
                </script>

            <div class="col-md-3">
              <div class="form-group">
                <b><label class="col-form-label" for="inputDefault">Horimetro da Troca</label></b>
                <input class="form-control" name="horimetroca" id="horimetroca" type="text">
              </div>
            </div>

            <div class="col-md-3">
              <div class="form-group">
                <b><label class="col-form-label" for="inputDefault">Horimetro da Proxima Troca</label></b>
                <input class="form-control" readonly="" name="proximatroca" id="proximatroca" type="text">
              </div>
            </div>


            <div id="resultados"></div> 
  • in the one that Oce sent has no way to stay, like I put the horimetro and as soon as press the TAB or select another input, it already inserted only without having to put this add button.

  • Thank you for the time devoted in this doubt, sorry the delay to accept the answer, it worked straight congratulations...

  • @Diogocarvalho, blz, I edited the answer by adding more options blur keyup change and without the button add

  • the.php search will stay the same without change?

  • @Diogocarvalho, exact, the buscaVeiculo.php is the same, no change!!

  • See ate form code

  • @Diogocarvalho, I don’t understand

  • for="inputDefault">Vehicle</label></b> <select name="idVeiculo" class="form-control Select2" id="idVeiculo" style="width"::100%;" > <option value="" Selected>Select</option> <?php $resultipo = "SELECT * FROM vehicles"; $resultadotype = mysqli_query($Conn, $resultipo); while ($Row = mysqli_fetch_assoc($resultadotype)) ! ? > <option value="<? php echo $Row['idVeiculo']; ? >"><? php echo $Row['prefix']; ? ></option> <?php } ?>

  • see my @leo-Caracciolo [link] form (https://anotepad.com/notes/emh62c)

  • @Diogocarvalho, I saw, but what is happening?

  • then it is not working, the doubt is, is it because of the select that is catching the idVeiculo?

  • @Diogocarvalho, I will put provisionally in the answer how it should work. If it works let me know that I withdraw from the answer pq is not the focus of the question.

  • all right, okay...

  • @Diogocarvalho, note the classes and ids so that they are correct

  • OK, thank you gave everything right.... thanks for the attention and help. you really were the classes and ids I only had to make a change to the search placeVeiculo.php changed only after Where $sql = $connected->prepare("SELECT review FROM vehicles Where idVeiculo='$Prefix'");

  • @Diogocarvalho, blz, if you can put the right one in anotepad.com for me to see the modifications

  • ready is already there, see how the modifications in the form

  • @Diogocarvalho, very good, but I did a little different, see in the answer I edited.

  • Wonderful got showww !!! congratulations for the dedication...

Show 14 more comments

Browser other questions tagged

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