David
David

Reputation: 39

PHP/HTML Change Text if Dropdown Menu option is checked

I'm working on like a Shop Page, where you can choose how long you want to buy the service.

There is a Dropdown Menu with 3 Options:

How can I do :

If the option 3 Weeks is clicked, the price(simple text) automatically changes to 5 dollars and 6 Weeks to 10 Dollars or something like this?

All price changes are done by me.

I would like to know how can I change exampletext1 to exampletext2 by choosing something from my dropdown menu ?

Upvotes: 3

Views: 856

Answers (2)

Kittu
Kittu

Reputation: 31

Here's a small algorithm that will give you a basic idea:

<!DOCTYPE html>
<html>

<body>

  <p>Select a new car from the list.</p>

  <select id="mySelect" onchange="myFunction()">
    <option value="one">1 Week
      <option value="three">3 Week
        <option value="six">6 Week
  </select>

  <p id="price">Price: 1 dollars</p>

  <script>
    function myFunction() {
      /*
      You should get this price array from your PHP service dynamically
      whenever this page is requested.
      */
      var price = [];
      price['one'] = '1';
      price['three'] = '5';
      price['six'] = '10';


      var x = document.getElementById("mySelect").value;
      document.getElementById("price").innerHTML = "Price: " + price[x] + " dollars";

    }
  </script>

</body>

</html>

Upvotes: 3

EA-Lille
EA-Lille

Reputation: 561

Client side

To modify your page on client events (example:click, select change) without reloading all the page, you have to use a client side langage like JavaScript.

Server side

PHP is used only on server side. It's means that PHP is executed before your page is sent to user and can't catch action from user without send a new request to the server (and reload the page).

Here is the example you asked (with javascript)

https://jsfiddle.net/9c1unscw/1/

<p>Select a period.</p>

<select id="mySelect" onchange="myFunction()">
  <option value="1">1 Week
  <option value="2">3 Weeks
  <option value="3">6 Weeks
</select>

<p id="demo">Estimated price: 5 dollars.</p>

<script type="text/javascript">
  function myFunction() {
      var x = document.getElementById("mySelect").value;
      var price = parseInt(x)*5;
      document.getElementById("demo").innerHTML = "Estimated price: " +price+" dollars.";
  }
</script>

Upvotes: 4

Related Questions