2013-01-08 53 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