Formulario with calculus

Asked

Viewed 216 times

2

I am now making an equipment rental site however I lack only the essentials of it to finish it, a form that allows to calculate the cost of the rental taking into account the price of the product, the quantity, and the days that will be used, a thing of the kind used in link, so far I have only the calendar on Javascript, The rest I can’t do for nothing.

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>   
  • And what is left to do? You are in error ? What is the way to calculate the rent? What code have you tried to do for this calculation? Try to be as specific as possible, so you can have an answer to your problem.

  • With this code I can select the start and end date and it’s just what I have, now I have to calculate the cost of a particular product (being that you can rent more than 1 piece, can be x recorders) during the period of time that the person selects, for example if one wants to rent 3 recorders of 150,00€/per day +IVA (450,00€) for 3 days I know that will have to give 1080€ I do not know the relation of this last parameter. I am missing the code that allows me to do this calculation I hope this is useful.

2 answers

1


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

The most direct way would then be to create a function and call it in 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 directly subtracting the final date by the initial one, which gives a result in milliseconds and convert to days by dividing by the correct factors. With days going from one date to another, calculate the value based on price, quantity and Iva, thus:

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>

<script src="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 date formatting to datepicker, which was not yet in use.

It remains to naturally contemplate the rest of the html that refers to quantity, price and these values that I have put as fixed to exemplify, and acquire them in the function.

0

I inserted this code in the HTML file and replaces the parameters I found necessary, however something is missing because it does not present 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>

<script src="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>

Browser other questions tagged

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