-2

I have a select option to add accessories to a product. What I want to do is recalculate the price without have to refresh the page. This is what I'v got so far:

  <form action="" method="post">
    <select name="option" onchange="this.form.submit()">
    <option value="15">Acc1</option>
    <option value"30">Acc2</option>
    <option value"45">Acc3</option>
    </select>
    </form>
$oldprice ='678';
    $option = $_POST['option'];
    $newPrice= $oldprice + $option;

This works great, however it has to refresh the page. Is there a way to recalculate the new price without having to refresh the page. And also use the option value in other places on the page for example

If ($_POST['option] == '15'){ \do something}

Any help welcome

Ria
  • 516
  • 6
  • 24

2 Answers2

0

You could use ajax or if the needed information is already in the page which it seems to be based on your example code, then you could change the onchange to be a function:

onchange='updatePrice()'

Sample function code:

function updatePrice(){
    var e = document.getElementsByName("option")[0];
    var accessory_value = e.options[e.selectedIndex].value;
    //additional code to update the price where
}
  • Thanks for your reply, however I'm still not sure how to get the actual price to recalculate. I tries to put this $newPrice = $oldprice + $option where it said //addition code here but that is not the right way as the price turns to 0 if there is no option selected – Ria Jun 10 '17 at 12:44
  • `$newPrice = $oldprice + $option` is PHP code not Javascript code. The additional code should be Javascript code that selects the element that displays the price and updating its value or innerHTML. You will want to keep the base price stored somewhere in case the user changes the accessory. – Peter Schweitzer Jr Jun 10 '17 at 12:52
  • The problems you probably guessed is that i'm not very familiar with Javascript, so to be honest I have not much of an idea where to start here. – Ria Jun 10 '17 at 13:00
0

Hook onchange event in select tag.

Ex:

<select onChange="calculate(e)">
   // option here
</select>

*.js:

function calculate(e) {
    console.log(e.target.value);
}
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42