将 $programDates_items 的结构更改为如下对象:
var values = {animation: ["January 1, 2018", "April 28, 2018"],
gameDesign: ["February 20, 2018", "June 28, 2018", "October 20, 2018"]};
您的问题的解决方案是:
$( "#program_of_interest" ).on('change', function(e) {
$("#start_date").empty();
(values[$(this).val()] || ['Start Date']).forEach(function(ele, idx) {
$("#start_date").append($('<option/>', {text: ele, value: ele}));
})
});
var values = {animation: ["January 1, 2018", "April 28, 2018"], gameDesign: ["February 20, 2018", "June 28, 2018", "October 20, 2018"]};
$( "#program_of_interest" ).on('change', function(e) {
$("#start_date").empty();
(values[$(this).val()] || ['Start Date']).forEach(function(ele, idx) {
$("#start_date").append($('<option/>', {text: ele, value: ele}));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="program_of_interest" name="program_of_interest" required="">
<option value="">Program of Interest</option>
<option value="animation">Animation</option>
<option value="gameDesign">Game Design</option>
</select>
<select id="start_date" name="start_date" required="">
<option value="">Start Date</option>
</select>
相反,如果您的 $programDates_items 是一个数组数组,例如:
var values = [["January 1, 2018", "April 28, 2018"], ["February 20, 2018", "June 28, 2018", "October 20, 2018"]];
解决办法可以是:
$( "#program_of_interest" ).on('change', function(e) {
$("#start_date").empty();
(values[this.selectedIndex - 1] || ['Start Date']).forEach(function(ele, idx) {
$("#start_date").append($('<option/>', {text: ele, value: ele}));
})
});
var values = [["January 1, 2018", "April 28, 2018"], ["February 20, 2018", "June 28, 2018", "October 20, 2018"]];
$( "#program_of_interest" ).on('change', function(e) {
$("#start_date").empty();
(values[this.selectedIndex - 1] || ['Start Date']).forEach(function(ele, idx) {
$("#start_date").append($('<option/>', {text: ele, value: ele}));
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="program_of_interest" name="program_of_interest" required="">
<option value="">Program of Interest</option>
<option value="animation">Animation</option>
<option value="gameDesign">Game Design</option>
</select>
<select id="start_date" name="start_date" required="">
<option value="">Start Date</option>
</select>
问题是我的程序/日期数组是一个 php 数组,因此我不能在 javascript 函数中使用它,除非我有误解。
为了获得第一个对象,在PHP中你需要这样写:
$programDates_items = json_encode(array('animation' => array(0 => "January 1, 2018", 1 => "April 28, 2018"),
'gameDesign' => array(0=>"February 20, 2018", 1=>"June 28, 2018", 2=>"October 20, 2018")));
在javascript中你可以得到变量写法:
var values = <?php echo $programDates_items; ?>;
如果你需要第二个对象,你需要在 PHP 中编写:
$programDates_items = json_encode(array(0 => array(0 => "January 1, 2018", 1 => "April 28, 2018"),
1 => array(0=>"February 20, 2018", 1=>"June 28, 2018", 2=>"October 20, 2018")));
在javascript中:
var values = <?php echo $programDates_items; ?>;
详情可以看json_encode