'JQuery .change() not working with dropdown list

My code function is if a users select an option on dropdown list. It will load a php file based on users selected.

<html>

<head>
<script 
src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script>
$('#dropdownopt').change(function(){
    var selectedValue = $(this).val();
    if (selectedValue === "1"){
        $("#maindivv").load("iteratemonths.php");
    }
});
</script>
</head>

<body>
<form><select id = "dropdownopt">
<option value = ""></option>
<option value = "1">iteratemonths</option>
<option value = "2">test</option>
</select>
</form>
<br>
<div id="maindivv"></div>
</body>
</html>

What's wrong with my code? If I select iteratemonths it just shows blank page even though I double check the iteratemonths.php existed.



Solution 1:[1]

You forgot the .ready() method.

$(document).ready(function(){  
$('#dropdownopt').change(function(){
    var selectedValue = $(this).val();
    if (selectedValue === "1"){
        $("#maindivv").load("iteratemonths.php");
    }
});
});

Solution 2:[2]

1st : wrap your jquery code into inside the document.ready.

2nd : Why your code not working means your trying to bind the event to element before it available . so it's not working .

<script>
$(document).ready(function(){
  $('#dropdownopt').change(function(){
      var selectedValue = $(this).val();
      if (selectedValue === "1"){
         $("#maindivv").load("iteratemonths.php");
      }
  });
});

Solution 3:[3]

$(function(){
$('#dropdownopt').on('change',function(){
    var selectedValue = $('#dropdownopt option:selected').val();
    if (selectedValue === "1"){
    console.log('matched!');
    }
    
    console.log(selectedValue);
});

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<select id = "dropdownopt">
<option value = ""></option>
<option value = "1">iteratemonths</option>
<option value = "2">test</option>
<option value = "3">test3</option>
<option value = "4">test4</option>
<option value = "5">test5</option>
</select>

try like this way. I hope it helps you

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mkrieger1
Solution 2 JYoThI
Solution 3 Neeraj Pathak