动态/相关输入框

时间:2010-06-17 14:25:51

标签: javascript

如何只在我从下拉框中选择一个值时才会出现一个输入框?

谢谢你, 塞巴斯蒂安

EDIT-1:

谢谢你的帮助。 但是来自sushil bharwani的例子对我来说是最好的,因为我还需要用文本框显示文本。

但是有了这个例子我有一个问题。文本框和文本框看起来都在同一个单元格中,因此它们会弄乱我的表单布局。 有什么想法吗?

感谢,

4 个答案:

答案 0 :(得分:0)

您需要定义select的onchange属性以检查所选选项的文本(或值):

<script type="text/javascript">
 function checkSelect(el) {
  if (el.options[el.selectedIndex].text.length > 0)
   document.getElementById('text1').style.display = 'block';
  else
   document.getElementById('text1').style.display = 'none';
 }
</script>

<select onchange="checkSelect(this)">
 <option></option>
 <option>Val 1</option>
</select> 

<input type="text" id="text1" style="display:none" />

有关更多详细信息,您可以阅读有关HTML DOM对象以及如何通过javascript访问它们的更多信息:

http://www.w3schools.com/jsref/default.asp

答案 1 :(得分:0)

考虑文本框应该在选择选项2时显示

下拉框

<select id="dropBox" size="1" onChange="dropBoxChng();">
    <option value="1">Choice 1</option>
    <option value="2">Choice 2</option>
    <option value="3">Choice 3</option>
    <option value="4">Other</option>
</select>

输入框

<input type="text" id="txtBox" style="display:none">

onchange功能

function dropBoxChng(){
    if(document.getElementById('dropBox').value == 2){
        document.getElementById('txtBox').style.display = 'block';
    }
}​

演示here

答案 2 :(得分:0)

<html>
<head>
<style type="text/css">
input {
    font-family: Arial, Sans-Serif;
    font-size: 13px;
    margin-bottom: 5px;
    display: block;
    padding: 4px;
    border: solid 1px #85b1de; 
    width: 300px;
    background-color: #EDF2F7;
}

option {
 color: white;
 background-color: blue;
}

.even {
  background-color: red;
  color: blue;
}
</style>
<script>
function replaceElement(){
    var select=document.getElementById('mySelectMenu');
    var chosenoption=select.options[select.selectedIndex];
    var oChild= document.getElementsByTagName('input');  
    var br1= document.getElementsByTagName('br');
    var temp=br1.length; 
    for(var i=0; i<temp; i++){ 
       alert("remove input box " + i);
       myform.removeChild(oChild[0]); 
       alert("remove br " + i);
       myform.removeChild(br1[0]);
    }
    for(var i=0; i<chosenoption.value; i++){
       alert("add br " + i);
       var br2 = document.createElement('br');
       myform.appendChild(br2); 
       alert("add input box " + i);
       var oNewChild=document.createElement('input');
       oNewChild.type='text';
       oNewChild.size=6;
       myform.appendChild(oNewChild);  
    }
}
</script>
</head>
<body>
<form id="myform">
<select id="mySelectMenu" onchange="replaceElement()">
    <option value="1">1</option>
    <option value="2" class="even">2</option>
    <option value="3">3</option>
    <option value="4" class="even">4</option>
    <option value="5">5</option>
</select>
</form>
</body>
</html>

答案 3 :(得分:-1)

相关问题