seyma
seyma

Reputation: 1

Javascript If Else Condition Not Working

I show a result after an "if else" condition control selection. But I want show only one result if I change selected item in the second box. How can I solve this problem ?

For Example:

I should show result if I select first item from first select box AND I select second item from second select box (It's not a problem) AFTER

I should show result if I select second item from first select box AND I select second item from select box

But I showed first and second result at the same time. I only want to show one result at a time. I think my if else conditions are wrong.

function Compare(sel1, sel2) {
  if (sel1 == 'A' && sel2 == '1') {
    $('#first').show();
    $('#first1').prop('disabled', false);
  } else if (sel1 == 'A' && sel2 == '2') {
    $('#second').show();
    $('#second1').prop('disabled', false);
  }
}

var $sel1 = $("#sel1"),
    $sel2 = $("#sel2");


$("#sel1, #sel2").change(function() {
  Compare($sel1.val(), $sel2.val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<div class="form-group">
  <select class="form-control" id="sel1" name="sel1">
    <option selected> </option>
    <option value="A">A1 </option>
  </select>
</div>

<div class="form-group">
  <select class="form-control" id="sel2">
    <option selected> </option>
    <option value="1">1 </option>
    <option value="2" > 2 </option>
  </select>
</div>

<div class="form-group" id="first" style="display: none;">
  <input class="form-control" rows="1" name="first" id="first1" readonly value="'78'" disabled></div>
<div class="form-group" id="second" style="display: none;">
  <input class="form-control" rows="1" name="second" id="second1" readonly value="'78000'" disabled></div>

Upvotes: 0

Views: 90

Answers (2)

jsanchezs
jsanchezs

Reputation: 2070

Hide the other control when you selected another :

function Compare(sel1, sel2) {
  if (sel1 == 'A' && sel2 == '1') {
    $('#first').show();
    $('#second').hide();
    $('#first1').prop('disabled', false);
  } else if (sel1 == 'A' && sel2 == '2') {
    $('#second').show();
    $('#first').hide();
    $('#second1').prop('disabled', false);
  }
}

var $sel1 = $("#sel1"),
    $sel2 = $("#sel2");


$("#sel1, #sel2").change(function() {
  Compare($sel1.val(), $sel2.val());
});

Upvotes: 3

B. Fleming
B. Fleming

Reputation: 7220

You're showing elements, but never hide them again. You'll want to hide elements that you no longer wish to show, otherwise they will continue to display.

Upvotes: 0

Related Questions