2010-06-17 83 views
0

如何制作仅在从下拉框中选择值时才出现的输入框?动态/依赖输入框

谢谢你, 塞巴斯蒂安

编辑-1:

谢谢你们的帮助。 但sushil bharwani的例子最适合我,因为我也需要在文本框中显示文本。

但与那个例子我有一个问题。文本和文本框看起来像是在同一个单元格中,所以他们搞乱了我的表单布局。 有什么想法吗?

感谢,

回答

0

你要定义选择的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

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

的平变化函数

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

演示文本框应显示here

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>