Oussama
Oussama

Reputation: 71

Show/Hide div based on select option

Here's my code :

HTML :

<Select id="colorselector">
   <option value="red-1">Red</option>
   <option value="yellow-2">Yellow</option>
   <option value="blue-2">Blue</option>
   <option value="black-1">Black</option>
</Select>
<div id="-1" class="colors" style="display:none"> Div1... </div>
<div id="-2" class="colors" style="display:none"> Div2.. </div>

JS :

$(function() {
    $('#colorselector').change(function(){
        $('.colors').hide();
        $('#' + $(this).val()).show();
    });
});

What I want : when I select an option that contains "-1" the first div will appears, and the second div will disappear. And If I select an option that contains "-2" the firs div will disappear, and the second one will appears.

Upvotes: 0

Views: 1601

Answers (2)

Pranav C Balan
Pranav C Balan

Reputation: 115212

Use split() to get the number

$(function() {
  $('#colorselector').change(function() {
    $('.colors').hide();
    $('#-' + $(this).val().split('-')[1]).show();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<Select id="colorselector">
  <option value="red-1">Red</option>
  <option value="yellow-2">Yellow</option>
  <option value="blue-2">Blue</option>
  <option value="black-1">Black</option>
</Select>
<div id="-1" class="colors" style="display:none">Div1...</div>
<div id="-2" class="colors" style="display:none">Div2..</div>

Upvotes: 2

Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10179

Try this:

JS:

$("#colorselector").change(function(){
    if((this.options[this.selectedIndex].value).indexOf("-1") > -1) {
        $("#-2").hide();
        $("#-1").show();
    }
    else {
        $("#-1").hide();
        $("#-2").show();
    }
});

Demo.

Upvotes: 1

Related Questions