[英]Select dynamically created <select option> with php variable
昨天我学习了如何使用javascript动态创建选择选项:
<select name="dateformat" onchange="change_date();" id="dateformat">
</select>
var dateformat = document.getElementById('dateformat');
dateformat.options[dateformat.options.length] = new Option(month + "/" + day + "/" + fullyear, "M/d/yyyy");
dateformat.options[dateformat.options.length] = new Option(monthwz + "/" + daywz + "/" + fullyear,"MM/dd/yyyy");
dateformat.options[dateformat.options.length] = new Option(day + "/" + month + "/" + fullyear,"d/M/yyyy");
我不知道这是否是唯一的方法,而javascript代码不能包含在代码块中,但是我不知道如何选择适当的选项。 从PHP我查询用户的设置,例如MM / dd / yyyy,因此在页面加载时我需要选择第二个选项。
我可以通过静态选择选项来做到这一点,例如
<option value="Business" <?php if($category == 'Business'): ?> selected="selected"<?php endif; ?> >Business</option>
但是在这种情况下,select选项是动态创建的。
您可以重写代码以使其更加美观:
var dateformat = document.getElementById("dateformat"),
options = [{
text: month + "/" + day + "/" + fullyear,
value: "M/d/yyyy"
}, {
text: monthwz + "/" + daywz + "/" + fullyear,
value: "MM/dd/yyyy"
}, {
text: day + "/" + month + "/" + fullyear,
value: "d/M/yyyy"
}];
for (var i = 0, len = options.length; i < len; i++) {
var option = options[i],
element = new Option(option.text, option.value);
dateformat.options[dateformat.options.length] = element;
}
// one way to set the selected value:
dateformat.value = <?php print json_encode($value); ?>;
演示: http : //jsfiddle.net/vPerj/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.