Form with calculation

2

I am now making an equipment rental website, however, I only have the essentials to finish it, a form that allows me to calculate the cost of the rent taking into account the price of the product, the quantity, and the days will be used, something like the one used in link , so far I have just the calendar in JavaScript , which is as I show below, the rest I can not do anything either.

Code:

<script>
  $( function() {
    var dateFormat = "dd/mm/yy",
      from = $( "#from" )
        .datepicker({
          defaultDate: "+1w",
          changeMonth: true,
          numberOfMonths: 2
        })
        .on( "change", function() {
          to.datepicker( "option", "minDate", getDate( this ) );
        }),
      to = $( "#to" ).datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2
      })
      .on( "change", function() {
        from.datepicker( "option", "maxDate", getDate( this ) );
      });


function getDate( element ) {
  var date;
  try {
    date = $.datepicker.parseDate( dateFormat, element.value );
  } catch( error ) {
    date = null;
  }

  return date;
    }
  } );
  </script>


  <body>
<label for="from">De</label>
<input type="text" id="from" name="from" placeholder="Data início ">
<label for="to">a</label>
<input type="text" id="to" name="to" placeholder="Data final de aluguer">
</body>   
    
asked by anonymous 07.09.2017 / 11:12

2 answers

1

You can do the calculation you want within the change methods of each datepicker to be calculated each time the person changes one of the dates.

The most direct way would be to create a function and call it at each of these sites:

  from = $( "#from" )
    ...
    .on( "change", function() {
      to.datepicker( "option", "minDate", getDate( this ) );
      calcula(); //calcula aqui 
    }),
  to = $( "#to" )
  ...
  .on( "change", function() {
    from.datepicker( "option", "maxDate", getDate( this ) );
    calcula(); //e aqui
  });

And this calculation function can calculate the days by subtracting directly the end date by the initial, which gives a result in milliseconds and convert to days dividing by the correct factors. With the days ranging from one date to another, calculate the value based on the price, quantity and VAT, like this:

function calcula() {
  //se não tem as duas datas aborta
  if (to.datepicker('getDate') == null || from.datepicker('getDate') == null) return 0;

  //calcular a diferença entre as duas datas em milisegundos
  let diferenca = to.datepicker('getDate') - from.datepicker('getDate');

  diferenca =  diferenca / 1000 / 60 / 60 / 24; //converter para dias
  const valor = 150;
  const quantidade = 3;
  const iva = 0.23;

  let total = valor * quantidade * diferenca * (1+iva); //fazer o calculo

  return total;
}

Example:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
<script>
  $(function() {
    var dateFormat = "dd/mm/yy",
      from = $("#from")
      .datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: dateFormat //formatação da data estava em falta
      })
      .on("change", function() {
        to.datepicker("option", "minDate", getDate(this));
        calcula();
      }),
      to = $("#to").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 2,
        dateFormat: dateFormat //formatação da data estava em falta
      })
      .on("change", function() {
        from.datepicker("option", "maxDate", getDate(this));
        calcula();
      });

    function calcula() {
      if (to.datepicker('getDate') == null || from.datepicker('getDate') == null) return 0;

      let diferenca = to.datepicker('getDate') - from.datepicker('getDate');
      diferenca =  diferenca / 1000 / 60 / 60 / 24; //para dias
      const valor = 150;
      const quantidade = 3;
      const iva = 0.23;
      
      let total = valor * quantidade * diferenca * (1+iva);

      console.log('${quantidade} artigos por ${diferenca} dia(s) ficam a ${total}€');
      return total;
    }

    function getDate(element) {
      var date;
      try {
        date = $.datepicker.parseDate(dateFormat, element.value);
      } catch (error) {
        date = null;
      }

      return date;
    }
  });
</script>


<body>
  <label for="from">De</label>
  <input type="text" id="from" name="from" placeholder="Data início ">
  <label for="to">a</label>
  <input type="text" id="to" name="to" placeholder="Data final de aluguer">
</body>

In the example I also applied the formatting of dates in datepicker , which was not yet in use.

    

07.09.2017 / 14:55
0

I inserted this code into the HTML file and replaced the parameters I found necessary, however something is missing because it does not show me any result Thank you

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Documento sem título</title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU=" crossorigin="anonymous"></script>
</head>
<script>
	
  $(function() {
    var dateFormat = "dd/mm/yy",
      from = $("#from")
      .datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 1,
        dateFormat: dateFormat //formatação da data estava em falta
      })
      .on("change", function() {
        to.datepicker("option", "minDate", getDate(this));
        calcula();
      }),
      to = $("#to").datepicker({
        defaultDate: "+1w",
        changeMonth: true,
        numberOfMonths: 1,
        dateFormat: dateFormat //formatação da data estava em falta
      })
      .on("change", function() {
        from.datepicker("option", "maxDate", getDate(this));
        calcula();
      });

    function calcula() {
      if (to.datepicker('getDate') == null || from.datepicker('getDate') == null) return 0;

      let diferenca = to.datepicker('getDate') - from.datepicker('getDate');
      diferenca =  diferenca / 1000 / 60 / 60 / 24; //para dias
      var valor = $("#valor")
      var quantidade = $("#qtd")
      var iva = 0.23;
      
      let valortotal = valor * quantidade * diferenca * (1+iva);

      console.log('${quantidade} artigos por ${diferenca} dia(s) ficam a ${total}€');
      return total;
    }

    function getDate(element) {
      var date;
      try {
        date = $.datepicker.parseDate(dateFormat, element.value);
      } catch (error) {
        date = null;
      }

      return date;
    }
	  
  });
	
	
	
</script>

<body>
 
  <label for="from">De</label>
  <input type="text" id="from" name="from" placeholder="Data início ">
  <label for="to">a</label>
  <input type="text" id="to" name="to" placeholder="Data final de aluguer">
  
   <span class="valor" id="valor"><span>Preço: </span><span class="valor">150.00<span class="euro">&euro;</span></span></span></p>
  
  <span class="valortotal" id="valortotal"><span>Valor Total: </span><span class="valortotal">150.00<span class="euro">&euro;</span></span></span></p>
  
  <label for="quantidade"> Quantidade: </label>
  <input type="number" step="1" min="1" max="" name="qtd" id="qtd" value="1" title="Qtd" class="input-text qtd text"  size="4" pattern="[0-9]*" inputmode="numeric" >
	
	</input>
	</input>
	</input>
	
</body>


</html>
    
07.09.2017 / 17:21