我正在嘗試創建一個Javascript函數,它將從一個選擇字段中取值,然後使用它來比較JSON數組。如果有任何數組元素與用戶選擇的值匹配,那麼函數會將這些值添加到另一個選擇字段。使用Javascript修改選擇字段選項
邏輯:使用 「平變化」 HTML屬性從選擇字段
- 激活功能如果數組值==選擇比較這個值來JSON陣列
- 值,附加到其他選擇字段
代碼:
//this function modifies a select field depending on what value was selected by its predecessor
function tariffs()
{
//variable selection equals the selected value chosen by the user in that field
var selection = document.getElementById('tariff_net').options[document.getElementById('tariff_net').selectedIndex].value
//for loop to go through JSON values to compare with the value chosen by the user
for(var i = 0; i < values.preset_name.length ; i++)
{
//if the JSON value equals the user selected value
if (values.preset_name[i] == selection)
{
//append it to the "tariff_name" select field
var option = values.preset_name[i];
var selectfield = document.getElementById('tariff_name');
selectfield.appendChild(option);
}
}
}
下面是該兩個選擇字段的截圖(在上面的人會影響到下選擇字段選項)
目前我的代碼不工作,我得到一個Javascript錯誤:
Could not convert JavaScript argument arg 0 [nsIDOMHTMLInputElement.appendChild] [Break On This Error] selectfield.appendChild(option);
我也想知道如何才能使Javscript刷新所有值的選擇字段,然後重新填充它。這將防止每當函數被調用時大量重複的選項。
由於
你可以發佈一個[JS小提琴演示](http://jsfiddle.net)顯示你到目前爲止的嘗試嗎? – 2012-01-12 10:11:45
@DavidThomas我可以嘗試,但問題是我的領域是使用PHP生成的,所以是我的JSON – kaleeway 2012-01-12 10:14:05
然後嘗試看看您是否可以儘可能地使用靜態HTML/JS來模擬。我知道這並不理想,但沒有看到發生了什麼事情,很難提供幫助。而且,在沒有Ajax的情況下再現問題時,至少可以知道錯誤來自何處。 – 2012-01-12 10:17:02