Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript update price select onchange

I'm working on a simple car reservation system for a first year project, which is among others an introduction to javascript.

On page one the values the user entered are passed to page 2 with php, and my javascript below is working correctly to calculate the rental price.

My Problem

However, on page 2 the user can edit their booking, i.e. upgrading car type. Which should result in either a price increase or decrease depending on the carGroup selected by user.

My problem when im adding the onchange to the select element for carGroup the price is not changing and im getting no errors which is not making the situation any easier to debug.

The code below is pretty basic, I would greatly appreciate it, if someone could give it a scan and perhaps advise where I'm going wrong.

UI

enter image description here

Javascript

function calcPrice() {
  var oneDay = 24 * 60 * 60 * 1000;
  var firstDate = document.getElementById("firstDate").value;
  var secondDate = document.getElementById("secondDate").value;
  var date1 = firstDate.substring(0, 11);
  var date2 = secondDate.substring(0, 11);
  date1 = date1.replace(/\//g, ",");
  date2 = date2.replace(/\//g, ",");

  var firstDate = new Date(date1);
  var secondDate = new Date(date2);

  var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
  //calculate rental price
  var price;
  var dayRate;
  var carGroup = document.getElementById("group").value;

  //change values to increase or decrease price
  var a = 250;
  var b = 500;
  var c = 750;
  var d = 1000;
  if (carGroup == 'a') {
    price = diffDays * a;
    dayRate = a;
  } else if (carGroup == 'b') {
    price = diffDays * b;
    dayRate = b;
  } else if (carGroup == 'c') {
    price = diffDays * c;
    dayRate = c;
  } else if (carGroup == 'd') {
    price = diffDays * d;
    dayRate = d;
  }

  document.getElementById("rentalInfo").innerHTML = diffDays + ' Day Rental, At: ' + dayRate + ' Per Day. <span style="color:red; font-weight:bold"> Total Price: ' + price + '</span>';
}

Html

         <select onChange="calcPrice()"name="carType" id="group">
            <option selected value="<?php echo $carType ?>"><?php echo $carType?></option>
            <option value="a">Group A (Hyundai I10)</option>
            <option value="b">Group B (VW POLO)</option>
            <option value="c">Group C (Corolla)</option>
            <option value="d">Group D (Bakkie)</option>
        </select>
    </div><!--formGroup-->

JSFIDDLE

I created a JSFIDDLE here, the only problem with my JSFIDDLE Is that The calcPrice() function should run on <body onload="calcPrice()"> which I suspect is not happening in JSFIDDLE

like image 682
Marilee Avatar asked Aug 18 '16 02:08

Marilee


People also ask

When onchange event triggers?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.

What is change event in JavaScript?

The JavaScript change event is an event type that gets executed when the focus on an element is changed. The change event of JavaScript inherits all the methods and properties of the Event.


2 Answers

Hey Marilee that was me in the fiddle with you! lol! So this may need some tweaking but one way to do it is to use event listeners instead. By putting this in an onload, it will run the function when a user hits the page - rendering the default days and values and price.

The keyup event listener may not be exactly what you want in that the price will be updating LIVE as the user adjusts their dates and you may not want that (just google around or check the docs to see if there is a event more suited to your needs - another option would be to add a button that runs the function to update when the user is finished adjusting) and the change eventlistener will call the function anytime the dropdown select is changed.

window.onload = function() {
        document.querySelector("#firstDate").addEventListener("keyup", calcPrice);
        document.querySelector("#secondDate").addEventListener("keyup", calcPrice);
        document.querySelector("#group").addEventListener("change", calcPrice);

        function calcPrice() {
          var oneDay = 24 * 60 * 60 * 1000;
          var firstDate = document.getElementById("firstDate").value;
          var secondDate = document.getElementById("secondDate").value;
          var date1 = firstDate.substring(0, 11);
          var date2 = secondDate.substring(0, 11);
          date1 = date1.replace(/\//g, ",");
          date2 = date2.replace(/\//g, ",");

          firstDate = new Date(date1);
          secondDate = new Date(date2);

          var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
          //calculate rental price
          var price;
          var dayRate;
          var carGroup = document.getElementById("group").value;

          //change const values to increase or decrease price
          var a = 250;
          var b = 500;
          var c = 750;
          var d = 1000;
          if (carGroup == 'a') {
            price = diffDays * a;
            dayRate = a;
          } else if (carGroup == 'b') {
            price = diffDays * b;
            dayRate = b;
          } else if (carGroup == 'c') {
            price = diffDays * c;
            dayRate = c;
          } else if (carGroup == 'd') {
            price = diffDays * d;
            dayRate = d;
          }

          document.getElementById("rentalInfo").innerHTML = diffDays + ' Day Rental, At: ' + dayRate + ' Per Day. <span style="color:red; font-weight:bold"> Total Price: ' + price + '</span>';
        }



      calcPrice()
      }

Also, in your code you are redeclaring the firstDate and secondDate variables when you reset them. No need to redeclare them.

Another way to do it would be to leave your code as it is and only put the event listeners and the function call in the page load.

window.onload = function() {
        document.querySelector("#firstDate").addEventListener("keyup", calcPrice);
        document.querySelector("#secondDate").addEventListener("keyup", calcPrice);
        document.querySelector("#group").addEventListener("change", calcPrice);

calcPrice()
      }
like image 163
HolyMoly Avatar answered Sep 20 '22 16:09

HolyMoly


window.onload = function()
{
  document.querySelector("#firstDate").addEventListener("keyup", calcPrice);
  document.querySelector("#secondDate").addEventListener("keyup", calcPrice);
  document.querySelector("#group").addEventListener("change", calcPrice);

  function calcPrice() {
    var oneDay = 24 * 60 * 60 * 1000;
    var firstDate = document.getElementById("firstDate").value;
    var secondDate = document.getElementById("secondDate").value;
    var date1 = firstDate.substring(0, 11);
    var date2 = secondDate.substring(0, 11);
    date1 = date1.replace(/\//g, ",");
    date2 = date2.replace(/\//g, ",");

    var firstDate = new Date(date1);
    var secondDate = new Date(date2);

    var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime()) / (oneDay)));
    //calculate rental price
    var price;
    var dayRate;
    var carGroup = document.getElementById("group").value;

    //change const values to increase or decrease price
    var a = 250;
    var b = 500;
    var c = 750;
    var d = 1000;
    if (carGroup == 'a') {
      price = diffDays * a;
      dayRate = a;
    } else if (carGroup == 'b') {
      price = diffDays * b;
      dayRate = b;
    } else if (carGroup == 'c') {
      price = diffDays * c;
      dayRate = c;
    } else if (carGroup == 'd') {
      price = diffDays * d;
      dayRate = d;
    }

    var innerHtml;

    if (isNaN(diffDays)) {
       innerHtml = "Invalid Date";
    } else {
       innerHtml = diffDays + ' Day Rental, At: ' + dayRate + ' Per Day. <span style="color:red; font-weight:bold"> Total Price: ' + price + '</span>';
    }

    document.getElementById("rentalInfo").innerHTML = innerHtml;
  }

  calcPrice();
};
<input type="text" value="08/20/2016" id="firstDate" />
<input type="text" value="08/22/2016" id="secondDate" />
<select class="" name="carType" id="group">
  <option value="a" selected>Group A (Hyundai I10)</option>
  <option value="b">Group B (VW POLO)</option>
  <option value="c">Group C (Corolla)</option>
  <option value="d">Group D (Truck)</option>
</select>

<p id="rentalInfo"></p>
like image 40
fulvio Avatar answered Sep 16 '22 16:09

fulvio