I'm trying to load dynamically a second select drop down based on the selection given from the first drop down. I tried from an example given here but can't seem to get it working on my own. The alert input value has changed shows but the input value has changed 2 message does not appear. Original example here: PHP MYSQL dynamic select box
<!doctype html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<select id="select1" onchange="createSelect2()">
<option value="">Select sth</option>
<option value="1">1st option</option>
<option value="2">2nd option</option>
<option value="3">3rd option</option>
</select>
<select id="select2" onchange="selectSelect2">
<option value="">Select from select1 first</option>
</select>
<script>
$('#select1').change(createSelect2);
$('#select2').change(selectSelect2);
function createSelect2(){
alert("The input value has changed.") ;
var option = $(this).find(':selected').val(),
dataString = "option="+option;
if(option != '')
{
alert("The input value has changed 2. The new value is: " + option);
$.ajax({
type : 'GET',
url : 'http://www.mitilini-trans.gr/demo/test.php',
data : dataString,
dataType : 'JSON',
cache: false,
success : function(data) {
var output = '<option value="">Select Sth</option>';
$.each(data.data, function(i,s){
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
$('#select2').empty().append(output);
},
error: function(){
console.log("Ajax failed");
}
});
}
else
{
console.log("You have to select at least sth");
}
}
function selectSelect2(){
var option = $(this).find(':selected').val();
if(option != '')
{
alert("You selected: "+option);
}
else
{
alert("You have to select at least sth");
}
}
</script>
</body>
</html>
The script seems correct. You just forgot to add the jQuery library.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<meta charset="utf-8">
<head>