2013-01-08 51 views
0

我有一個主要由複選框填充的表單。每個複選框都有一個ID「值」,對應於javascript數組中的項目。數組項包含一些將填充textarea的文本。如何分配數組變量來選擇框下拉選項?

我想包括一些下拉框來清理網站;然而,我似乎無法分配數組ID到下拉選項?這可以在選擇框選項中完成嗎?有沒有一種解決方案來模擬選擇框而不使用選項卡?

我的HTML基本上是:

<div> 
    <input type=checkbox id=array1 name=textArray></input> 
    <input type=checkbox id=array1 name=textArray></input> 
    <input type=checkbox id=array1 name=textArray></input> 
    ... 
    <select><option 1><option 2>...</select> 
    </div> 
    <div> 
    <form> 
    <textarea id=outPut></textarea> 
    </form> 
    </div> 

而我的JS是:

var textArray = { 

array1: 'some text here', 
array2: 'some more text', 
array3: 'some other text', 
... 
array90: 'the last text' 

}; 

// variable assigned to chosen item 
var selectedInputs = document.getElementsByName("textArray"); 
for (var i = 0; i < selectedInputs.length; i++) { 
    selectedInputs[i].onchange = function() { 
     chosenItem = this; 
     printText();   
    }; 
} 
// Script to add items to the Comments section text area 
var mytextbox = document.getElementById('outPut'); 
var chosenItem = null; 

function printText(){ 
    if(chosenItem !== null){ 
     mytextbox.value += textArray[chosenItem.id] + ""; 
     // resets the radio box values after output is displayed 
     chosenItem.checked = false; 
     // resets these variables to the null state 
     chosenItem = null; 
    } 
} 

我怎麼能一個項目在我的JS數組的選擇框選擇的一個相關聯?

回答

1

我發現很難理解您要求的內容,但I threw this together希望這會對您有所幫助。

重要的一點是

var selectNode = document.getElementById('select'); // <select id="select"> 
selectNode.onchange = function() { 
    if (selectNode.selectedIndex !== 0) { 
    chosenItem = selectNode.options[selectNode.selectedIndex]; 
    selectNode.selectedIndex = 0; 
    printText(); 
    } 
} 

,而不是使用ID屬性爲你在做什麼(我用數據我)。


我還想說,如果你正在清理代碼,這將是強烈重新考慮你是如何傳遞函數之間的變量的好時機;在全局命名空間中設置一個值,並在下一次調用時依賴它,只是要求麻煩(競爭條件,與其他代碼的衝突等)。

+0

對不起,沒有精確的措詞。我試圖做一個簡潔的介紹,而不用我的示例代碼太瘋狂。我會嘗試採取你的建議,看看它會如何適合。我將要實施的實際網站位於http://www.hematogones.com/BMbiopsies_3.html。 – user1837608

+0

另外,我閱讀了關於在我的HTML中使用任意屬性的內容,並且似乎在HTML5中使用了這種用法;不幸的是,我的許多用戶將無法訪問Chrome或Firefox,並且IE7和8都無法訪問。因此,我的代碼可能必須有點原始,以便所有人都可以使用它。 – user1837608

+0

@ user1837608我無法在IE7/8上進行測試,但我會希望'.getAttribute'能夠爲未知屬性工作,'.selectedIndex'能夠按照預期工作(IE6中的iirc只讀)。如果_onchange_觸發,那麼任何代碼都應該沒有問題。 –

0

<option value="whatever">1</option>這從一開始就是HTML的一部分。

+0

謝謝。我知道我可以這樣做,但它不適用於我的最終用戶在文本區域內構建文本的方式。 – user1837608