0

I am trying to create a simple calculate function and I don't understand what am I missing. When clicking on the button: "calculate price" nothing is happening. Do you know why?

What I am trying to do is that once the user clicks on calculate price, the calculate() function will run and display a message according to the conditions.

    <script>
function calculate(e) {
    var personType = document.getElementsById("selectbox");
    var ways = document.getElementById("one");
    var coupon = document.getElementById("coupon");
    var total = 0;
    if (personType == "child") {
        total = 30;
    }
    if (personType == "adult") {
        total = 40;
    }
    if (personType == "pensioner") {
        total = 25;
    }
    if (ways == "two") {
        total = total * 2;
        total = total - 10;
    }
    if (coupon.includes("19")) {
        total = total * 0.9;
        document.getElementById("error").innerHTML = total;
    }
    else {
        e.preventDefault();
        document.getElementById("error").innerHTML = "coupon is not valid";
    }
}
</script>


    <form action="activate.php" method="get">
    <select name="selectbox" id="selectbox">
        <option value="child" id="1">child</option>
        <option value="adult" selected id="2">adult</option>
        <option value="pensioner" id="3">pensioner</option>
    </select>
    <fieldset>
        <legend>Select Direction:</legend>
            <label for="optionradio" >One way</label>
            <input type="radio" id="radio" value="one" name="one">
            <label for="optionradio">Two way</label>
            <input type="radio" id="radio" value="two" name="one">
    </fieldset><br />
    <label for="coupon">Coupon code:</label>
    <input type="text" id="coupon" name="coupon"><br /><br />
    <input type="submit" value="buy a ticket">
</form>
<input type="button" value="calculate price" onclick="calculate()"><br />

<p id="error"></p>

Thank you.

1
  • BTW none of your if(..) conditions will work as you expect. you need to use two == or three === for equality in javascript. Commented Jun 18, 2021 at 9:43

3 Answers 3

1

With a few minor tweaks to your HTML & javascript you can refine the process as below.

The submit button will not submit the form whilst outside the form but need not be a submit type button at all. Change that to a regular button and call the javascript function externally rather than using the onclick=calculate() type of call as it makes the markup cleaner and easier to maintain.

Many of the IDs were redundant and some duplicated. In most cases IDs can be removed and elements targeted in a much simpler way - querySelector and querySelectorAll are super useful for this ~ especially when combined with additional flags such as the :checked as below for the ticket type radio button.

document.querySelector('[type="button"]').addEventListener('click',e=>{
  let msg='coupon is not valid';
  let oSel=document.querySelector('select[name="selectbox"]');
  let oTicket=document.querySelector('input[type="radio"][name="ticket"]:checked');
  let oCoupon=document.querySelector('input[type="text"][name="coupon"]');
  let total=0;
  
  if( oSel.value=='child' )total=30;
  if( oSel.value=='adult' )total=40;
  if( oSel.value=='pensioner' )total=25;
  
  if( oTicket.value=='two' ) {
    total*=2;
    total-=10;
  }
  if( oCoupon.value.includes('19') ){
    total *= 0.9;
    msg=total;
  }
  document.getElementById("error").innerHTML=msg;
});
<form action="activate.php">
    <select name="selectbox">
        <option value="child">child
        <option value="adult" selected>adult
        <option value="pensioner">pensioner
    </select>
    
    <fieldset>
        <legend>Select Direction:</legend>
        <label>One way<input type="radio" name="ticket" value="one" /></label>
        <label>Two way<input type="radio" name="ticket" value="two" /></label>
    </fieldset>
    
    <br />
    
    <label for="coupon">Coupon code:</label>
    <input type="text" name="coupon" />
    
    <br />
    <br />
    
    <input type="submit" value="buy a ticket">
    <br />
    <input type="button" value="calculate price" />
</form>

<p id="error"></p>

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you but I am trying to study Javascript before I move to jQuery. I agree with you it can be done much faster with jQuery.
The above is vanilla Javascript - no jQuery there at all
Oh ok, they did not teach us this at the university course. :/
No problem! Did it do what you were hoping for though that is the question?!
1

The calculate price button is not associated with any form so it doesn't submit anything. If you want to calculate the price you can make the submit button into a regular button and use onclick to trigger calculate.

<input type="button" value="calculate price" onclick="calculate()">

Looking another time at your code there are many other things preventing calculating price correctly.

  • assignment instead of comparison in if statements as pointed out by Jamiec. Use == or === to compare values and = to assign values to variables.
  • document.getElementById() doesn't return values of DOM elements. Use .value on a DOM object to get the value.
  • duplicate id's on the radio buttons prevent getting their value. By giving the buttons a unique value, you can get the buttons value with .checked

A working example:

<script>
function calculate() {
    var personType = document.getElementById("selectbox").value;
    var twoways = document.getElementById("radio2").checked;
    var coupon = document.getElementById("coupon");
    var total = 0;
    if (personType == "child") {
        total = 30;
    }
    if (personType == "adult") {
        total = 40;
    }
    if (personType == "pensioner") {
        total = 25;
    }
    if (twoways) {
        total = total * 2;
        total = total - 10;
    }
    if (coupon.value.includes("19")) {
        total = total * 0.9;
        document.getElementById("error").innerHTML = total;
    }
    else {
        document.getElementById("error").innerHTML = "coupon is not valid";
    }
    console.log(total)
}
</script>
    <form action="activate.php">
    <select name="selectbox" id="selectbox">
        <option value="child" id="1">child</option>
        <option value="adult" selected id="2">adult</option>
        <option value="pensioner" id="3">pensioner</option>
    </select>
    <fieldset>
        <legend>Select Direction:</legend>
            <label for="optionradio"value="one">One way</label>
            <input type="radio" id="radio1" name="radio" >
            <label for="optionradio" value="two">Two way</label>
            <input type="radio" id="radio2" name="radio" value="two">
    </fieldset><br />
    <label for="coupon">Coupon code:</label>
    <input type="text" id="coupon" name="coupon"><br /><br />
    <input type="submit" value="buy a ticket">
</form>
<input type="button" value="calculate price" onclick="calculate()"><br />
<p id="error"></p>

1 Comment

THANK YOU! Seems like my issue was a typo of getElementsById instead of getElementById HIGHLY APPRECIATED!
0

How about this ?

<button type="submit" onclick="calculate();">hide</button>

btw.

<form action="activate.php" method="get">

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.