显示/隐藏文本框


Show/Hide a text box

>我有这个代码,如果我从下拉列表中选择一个类别,则显示/隐藏文本框。它工作正常,但我想要的是,如果有人选择不同的类别,那么文本框就会消失或被另一个文本框替换。例如:如果我选择食物,则会出现一个文本框,如果我选择其他类别,则上一个文本框会再次隐藏而不会刷新整个页面。 到目前为止,我得到了什么:

<script language="javascript" type="text/javascript">
    function addSubject(){
        selectedSubject = document.getElementById('category').value
        if (selectedSubject == 'food'){
            document.getElementById('box').style.display = 'block';
        }
    }
</script>
<?
    include ('connect.php');
    $query="SELECT id, name FROM category ";
    $result=mysql_query($query);
?>
<form>
    <select name="category" id="category" onchange="addSubject()">
        <option>Select Category</option>
        <?php while($row=mysql_fetch_array($result)) { ?>
            <option value=<?php echo $row['id']?>><?php echo $row['name']?></option>
        <?php } ?>
    </select>
    <div class="box"  id="box" style="display: none;">
        <div>
            <span>Title :</span><input type="text" name="text" size="8" maxlength="7" />
        </div>
    </div>
</form> 

喜欢总是提前感谢

你有像

jquery这样的库吗? 如果是这样,您可以执行以下操作:

jQuery('#box').replaceWith('<newelement>')

请参阅他们的文档:http://api.jquery.com/replaceWith/

如果我正确理解您的问题,您可以使用这样的函数:

// Expects your SELECT element as EL
function addSubject( el ){
    // Gets current selected value, as well as all DIVs
    var newValu = el.value,
        kiddies = document.getElementById("options").childNodes,
        klength = kiddies.length, curNode;
    // Counts through all childNodes of the DIV container
    while ( klength-- ) {
      curNode = kiddies[klength];
      // If the current node is a DIV (avoid text nodes )
      if( curNode.nodeName == "DIV" )
        // If the current node id equals our selected value, show the node
        curNode.style.display = curNode.id == newValu ? "block" : "none" ;
    }
}

这要求您将div元素包装在容器中,并将this传递到onchange函数调用中:

<select onchange="addSubject(this)">
    <option>Box</option>
    <option>Food</option>
    <option>Stack</option>
</select>
<div id="options">
    <div id="Box">Box: <input type="text" /></div>
    <div id="Food">Food: <input type="text" /></div>
    <div id="Stack">Stack: <input type="text" /></div>
</div>​

演示:http://jsfiddle.net/8nFCB/