Namo Namo - 24 days ago 9
HTML Question

Selected option alert in jquery

I am trying to alert in the web page as per option selected.

But it is not working.

I tried:



$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").text();
if{
selectedCountry == "India" ;
alert("You have selected the language - Hindi");
}
elseif{
selectedCountry == "Nepal";
alert("You have selected the language - Nepali");
}

});
});

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<label>Select Country:</label>
<select class="country">
<option value="nepal">Nepal</option>
<option value="india">India</option>
</select>




Answer Source

You have so much syntax errors:

  • The condition of an if or else if statement is after the statement and is within parentheses.
  • The else-if statement is else if not elseif.

Here is a fix:

$(document).ready(function() {
  $("select.country").change(function() {
    var selectedCountry = $(".country option:selected").text();
    if (selectedCountry == "India") {
      alert("You have selected the language - Hindi");
    } else if (selectedCountry == "Nepal") {
      alert("You have selected the language - Nepali");
    }
  });
});
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<label>Select Country:</label>
<select class="country">
    <option value="nepal">Nepal</option>
    <option value="india">India</option>
</select>