如何分配数组变量来选择框下拉选项?

时间:2013-01-08 19:06:40

标签: javascript drop-down-menu html-select

我有一个主要由复选框填充的表单。每个复选框都有一个ID“值”,对应于javascript数组中的项目。数组项包含一些将填充文本区域的文本。

我想包含一些下拉框来清理网站;但是,我似乎无法为下拉选项分配数组ID?这可以在selectbox选项中完成吗?是否有解决方法来模拟选择框而不使用选项卡?

我的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数组中的项与其中一个selectbox选项相关联?

2 个答案:

答案 0 :(得分: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 属性用于您正在做的事情(我使用 data-i )。


我还想说,如果您正在清理代码,那么现在是强烈重新考虑如何在函数之间传递变量的好时机。在全局命名空间中设置一个值并在下一次调用中依赖它只是要求麻烦(竞争条件,与其他代码位的冲突等)。

答案 1 :(得分:0)

<option value="whatever">1</option>这从一开始就是HTML的一部分。