2013-03-27 130 views
0

昨天,我学会了如何动态地创建一个选择选项使用javascript:选择动态创建<选择选项>用PHP变量

<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选项是动态创建的。

+0

你可以使用'selectedIndex'的'select'节点上。 – 2013-03-27 16:41:22

回答

0

你可以重写你的代码更优雅:

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); ?>; 

DEMO:http://jsfiddle.net/vPerj/