0

I have a form which is largely populated by checkboxes. The checkboxes each have an ID "value" that corresponds to an item within a javascript array. The array items hold some text that will populate a textarea.

I would like to include some dropdown boxes to clean up the site; however, I cannot seem to assign an array ID to the dropdown options? Can this be done in a selectbox option? Is there a workaround to simulate a selectbox without using the tab?

My html is basically:

    <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>

And my js is:

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;
    }
}

How can I associate an item in my js array with one of the selectbox choices?

4

2 回答 2

1

我发现很难理解你在问什么,但我把它放在一起,希望它会有所帮助。

重要的是

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)。


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

于 2013-01-08T19:25:49.390 回答
0

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

于 2013-01-08T19:10:53.983 回答