0

After searching this site, found a way to make dependent dropdown menu using ajax easily (used "kartik dependent dropdown" plugin before, but it doesn't work with select2, so custom solution was needed). I can get dependent (child) dropdown menu working perfectly when any option is selected from parent dropdown, but can't get dependent dropdown to be displayed when page is loaded (need to click some option in parent dropdown first). Here's the code:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Dynamic Dependent Select Box</title>
<link href="css/styles.css" rel="stylesheet" />
<script src="ajax/jquery.min.js"></script>
<script src="ajax/plugins/forms/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".parent1").select2();
$(".child1").select2();

$(".parent1").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;

$.ajax
({
type: "POST",
url: "test_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("select.child1").html(html);
}
});
});
});
</script>
</head>
<body>
<select name="parent1" class="parent1">
<option value="1">something</option>
<option value="2" selected>something good</option>
<option value="3">who cares</option>
</select>
<select name="child1" class="child1">
</select>
</body>
</html>

Here's test_ajax.php source:

    <?php
if (!isset($_POST['id']))
{
    exit();
}
else
{
    echo "<option value=\"".$_POST['id']."\">".$_POST['id']."</option>";
}
?>
<option value="aaa">aaa</option><option value="bbb">bbb</option><option value="ccc">ccc</option>

How should I modify the code, so the initial value (<option value="2" selected>something good</option>) gets posted to test_ajax.php when page is loaded (so child dropdown isn't empty on page load)?

Found some examples on this page, but they were for version 3.x of select2, and the function used in examples is deprecated in version 4.x

Mindaugas Li
  • 911
  • 4
  • 13
  • 33

1 Answers1

1

You can just trigger the change event manually, which should cause your AJAX request to be sent.

if ($('select.parent1').val()) {
  $('select.parent1').trigger('change');
}
Kevin Brown
  • 36,829
  • 37
  • 188
  • 225