Javascript查找indexOf选择选项

时间:2014-03-08 12:21:30

标签: javascript

所以这就是我设法做的,使用文本框为我的选择添加字符串。 我现在如何使用第二个文本框来编写我在select中使用第一个文本框创建的字符串的一部分,并找到indexOf我输入的单词(indexOf需要出现在第二个文本框下面)?

注意:请回答最简单的Javascript答案。

    function addString(){
        var addTwoSelect = document.getElementById("select");
        var write = document.createElement("option");
        write.text = document.getElementById("txt").value;
        addTwoSelect.add(write);        
    }


<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select"><option value="0">Choose a string</option></select>

2 个答案:

答案 0 :(得分:1)

好的,所以只需要第二个输入框并计算indexOf

function addString(){
    var addTwoSelect = document.getElementById("select");
    var write = document.createElement("option");
    write.value = write.text = document.getElementById("txt").value;
    addTwoSelect.add(write);
}
function outputIndex() {
    var addTwoSelect = document.getElementById("select"),
        secondBox = document.getElementById("string"),
        out = document.getElementById("index");
    out.innerText = addTwoSelect.value.indexOf(secondBox.value);
}

<input type="text" id="txt"/>
<input type="button" value="add string" onclick="addString()"/>
<select id="select" onchange="outputIndex()"><option value="0">Choose a string</option></select>
<input type="text" id="string" oninput="outputIndex()"/>
<output id="index"></output>

答案 1 :(得分:0)

使用value的{​​{1}}属性!

<option>

var last = 0;
function addString(){
    var addTwoSelect = document.getElementById("select");
    var write = document.createElement("option");
    write.text = document.getElementById("txt").value;
    write.value = ++last;
    addTwoSelect.add(write);        
}
function outputIndex() {
    var addTwoSelect = document.getElementById("select"),
        out = document.getElementById("index");
    out.innerText = addTwoSelect.value;
}
相关问题