angel1108
angel1108

Reputation: 333

multiple if else condition in javascript

I'm not good in javascript so i was jud experimenting a code. I want to have a multiple condition with different equalization that will subtract a value. this is my sample code but it didn't function, only the first condition functioned.

  var input = document.getElementById("amount");

var first = 30;
var second = 50;
var third = 60;

input.addEventListener("keyup", function () {

    if (input = first) {
       document.getElementById('rebate').value = document.getElementById('amount').value - 2;
     }
    else if (input = second) {
      document.getElementById('rebate').value = document.getElementById('amount').value - 2.50;
     }
    else if (input = third) {
      document.getElementById('rebate').value = document.getElementById('amount').value - 3;
     }
});

function sum() {
        var txtFirstNumberValue = document.getElementById('txt1').value;
        var txtSecondNumberValue = document.getElementById('amount').value;
        var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
        if (!isNaN(result)) {
            document.getElementById('total').value = result;
        }
    }

html

 <div class="form-group">
                        <label for="amount">Amount</label>
                        <input type="text" id="txt1"  onkeyup="sum();" value="5" hidden>
                        <input type="text" class="form-control " id="amount" name="amount" placeholder="00" required onkeyup="sum();">
                    </div>

 <div class="row">
                <div class="col-xs-3">
                    <div class="form-group">
                        <label for="total">Total</label>
                        <input type="text" class="form-control" id="total" name="total" placeholder="00" required readonly >
                    </div>
                </div>
            </div>


<div class="row">
                <div class="col-xs-3">
                    <div class="form-group">
                        <label for="total">With Rebate</label>
                        <input type="text" class="form-control" id="rebate" name="rebate" required readonly >
                    </div>
                </div>
            </div>

It would be great guys if you could help me. ^^

Upvotes: 1

Views: 73

Answers (1)

theblindprophet
theblindprophet

Reputation: 7937

Replace all of your = with == inside the if statements.

Also, var input = document.getElementById("amount") only grabs a reference to the element, not the value.

So in your if statements you need to write input.value == first, etc

Here is a JSFiddle that work: https://jsfiddle.net/bbjpg9np/

  • When the the user types 30, "With Rebate 28"
  • When the the user types 50, "With Rebate 47.5"
  • When the the user types 60, "With Rebate 57"

Upvotes: 1

Related Questions