使用JavaScript的选项值

时间:2012-07-24 15:30:41

标签: javascript html forms

我有一个包含以下字段的表单:

<input type="text" name="text" id="text">

我希望JavaScript获取字段的值,所以我认为我应该使用以下代码:

<script language="javascript">
    function GetTextBoxValue(text)

    {

        alert(document.getElementById(text).value);

    }
//-->
</script>

此代码必须更改下拉选项的值。

<option value="value from JavaScript/text from the textbox">other</option>

文本框中的文本是否可能是选项的值?如果是的话,我在这里写的是选项值=“来自JavaScript的值”,这样它才能正常工作?

2 个答案:

答案 0 :(得分:1)

这是一个演示:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function setOptionValue() {
                document.getElementById("option").value = document.getElementById("text").value;
                document.getElementById("option").text = document.getElementById("text").value;
            }
        </script>
    </head>
    <body>
        <input id="text" />
        <select>
            <option id="option"></option>
        </select>
        <button type="button" onclick="setOptionValue()">Set a value in the text box and press me</button>
    </body>
</html> 

答案 1 :(得分:0)

好的,我看到了两个解决方案。第一个是实时值更新:

<select id="folder" name="folder">
   <option ...
   ... </option>
   <option id="otheroption" value="New">Other</option>
</select>
<div id="otherfolder" style="display:none">
   <label for="otherinput">New folder name:</label>
   <input id="otherinput">
</div>
<script> // here, or execute the following onload/ondomready
    document.getElementById("folder").onchange = function(e) {
        // I guess you have this piece of code already
        document.getElementById("otherfolder").style.display =
            this.options[this.selectedIndex].id == "otheroption" ? "" : "none";
    };
    document.getElementById("otherinput").onkeyup = function(e) {
        document.getElementById("otheroption").value = this.value;
    };
</script>

第二个是动态更改选择和输入框的name(具有完全相同的标记),以确定将folder参数发送到服务器的值:

    document.getElementById("folder").onchange = function(e) {
        var name = "folder",
            other = this.options[this.selected].id == "otheroption";
        document.getElementById("otherfolder").style.display = other ? "" : "none";
        document.getElementById("otherinput").name = other ? name : "";
        this.name = other ? "" : name;
    };