Omer Omer - 4 months ago 9
Javascript Question

Display different result if didn't find the ID in jQuery

I have a select menu and some divs associates with it. I want the select menu to hide / show divs according to the select menu value. But if the jQuery didn't find the associative div then it should alert some text.

Here is my code:



$('select').change(function(){
var div = $(this).val();
$('#results div').hide();
$('#' + div).show();
});

#results div {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select>
<option value="div_1">Div 1</option>
<option value="div_2">Div 2</option>
<option value="div_3">Div 3</option>
</select>

<div id="results">
<div id="div_1">Div 1</div>
<div id="div_2">Div 2</div>
</div>





As you can see in my example above there is no
DIV 3
so I want an alert saying that there is no
DIV 3
found.

Any kind of help appreciated :)

Answer

check this fiddle

$('select').change(function(){
     var div = $(this).val();
     $('#results div').hide();
    if($('#results').find('#' + div).length > 0){
      $('#' + div).show();
    } else{
      alert("not find")
    }
});