2011-04-21 192 views
1

嗨,我想創建JavaScript的下拉菜單,一旦我選擇的地方我打印輸出框中的一個將緯度的地方,在第二我會得到經度。我的問題是,我只能做到這一點輸出拉或Lon到輸入,所以我想知道有沒有辦法做到這一點,讓他們都打印?謝謝。這裏是我的代碼:下拉菜單與JavaScript?

<html> 
<script language="JavaScript"><!-- 
function onChange() { 
    var Current = 
    document.formName3.selectName3.selectedIndex; 
    document.formName3.Lat1.value = 
    document.formName3.selectName3.options[Current].value; 
    document.formName3.Lon2.value = 
    document.formName3.selectName3.options[Current].value; 


} 
//--></script> 
<body> 
<form 
    name="formName3" 
    onSubmit="return false;" 
> 
<select 
    name="selectName3" 
    onChange="onChange()" 
> 
<option 
    value="" 
> 
Find Place 
<option 
    value = "52.280431" 
    value ="-9.686166" 
> 
Shop 
<option 
value = "52.263428" 
    value="-9.708326" 
> 
Cinema 
<option 
value = "52.270883" 
    value="-9.702414" 
> 
Restaurant 
<option 
value = "52.276112" 
    value="-9.69109" 
> 
Hotel 
<option 
    value = "52.278994" 
    value="-9.6877" 
> 
Petrol Station 
</select> 
<br><br> 
Lat2 
<input 
    name="Lat1" 
    type="text" 
    value="" 
> 
Lon2 
<input 
    name="Lon2" 
    type="text" 
    value="" 
> 
</form> 
</body> 
</html 

回答

3

Option只有一個值,而不是兩個。

而不是使用你有什麼,而不是考慮提供一個空格分隔列表,您的選擇,例如:

<!-- make sure to close all your tags as shown below --> 
<option value = "52.280431 -9.686166">Shop</option> 

然後,你將需要打破他們在你的JavaScript

function onChange() { 
    var Current = 
    document.formName3.selectName3.selectedIndex; 
    var latLong = document.formName3.selectName3.options[Current].value; 
    // handle case where the value is "" 
    if (!latLong) { 
     document.formName3.Lat1.value = ""; 
     document.formName3.Lon2.value = ""; 
     return; 
    } 
    // split them on space 
    var latLongItems = latLong.split(" "); 
    // latLongItems[0] contains first value 
    document.formName3.Lat1.value = latLongItems[0]; 
    // latLongItems[1] contains second 
    document.formName3.Lon2.value = latLongItems[1]; 
} 

你可以在行動here中看到這一點。請注意,我通過在window.onload處理程序中附加所有處理程序而不是在HTML中使您的Javascript變得不那麼突兀。不顯眼的Javascript被認爲是Javascript的最佳實踐。

+0

這項工作就像我需要它非常感謝你:) – Sasha 2011-04-21 13:22:44