2013-03-27 134 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/