Rocks
Rocks

Reputation: 511

Show/Hide a text box

I have this code that Show/Hide a text box if I select a category from a dropdown list. It's working fine, but what I want is if someone selects a different category then the text box disappears or be replaced with another text box. EX: If I select food then a text box appear, and if I select a different category the previous text box hides again without refreshing the whole page. Here what I've got so far:

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

Like always thanks in advance

Upvotes: 2

Views: 5765

Answers (2)

Matt
Matt

Reputation: 477

Do you have a library such as jquery available? If so, you could do something like this:

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

See their documentation for this here: http://api.jquery.com/replaceWith/

Upvotes: 1

Sampson
Sampson

Reputation: 268424

If I understand your problem correctly, you could go with a function like this:

// 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" ;
    }
}

This requires you to wrap your div elements in an container, as well as pass this into your onchange function call:

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

Demo: http://jsfiddle.net/8nFCB/

Upvotes: 0

Related Questions