简体   繁体   中英

Hide input field until certain dropdown value has been selected

I'm trying to keep a textfield in HTML hidden until a certain value of a drop-down-list has been selected. I'm extremely bad at javascript, and I've been searching around for a solution for quite some time.

This is what I could scrape together so far:

Javascript code:

function newCustomerType()
{
    var ddl = document.getElementById("customerType");
    var selectedValue = ddl.options[ddl.selectedIndex].value;

    if (selectedValue == "new")
    {
        document.getElementById('newType').type = text;
    }
    else
    {
        document.getElementById('newType').type = hidden;
    }
}

HTML code:

<form id="newCustomer" name="newCustomer" method="post" action="">
<table>
    <tr>
        <td>Name:</td>
    </tr>
   <tr>
        <td><input type="text" name="customerName"/></td>
    </tr>
    <tr>
        <td>Type:</td>
    </tr>
    <tr>
        <td>
            <select id="customerType" name="customerType">
                <option value="existing">existing type</option>
                <option value="new">new type:</option>
            </select>
            <input type="hidden" id="newType" name="newType"/>
        </td>
    </tr>
    <tr>
    <tr>
        <td><input type="submit" value="Register"/></td>
    </tr>
</table>
</form>

This does not seem to work. What is it that I'm doing wrong? Any help would be greatly appreciated.

Please check this out http://jsfiddle.net/2AALG/

Change the input type to 'text' and set the stylesheet display = none

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

And add a change handler in javascript, and use it to change the style

var ddl = document.getElementById("customerType");
ddl.onchange=newCustomerType;
function newCustomerType()
{   
    var ddl = document.getElementById("customerType");
    var selectedValue = ddl.options[ddl.selectedIndex].value;


    if (selectedValue == "new")
    {   document.getElementById("newType").style.display = "block";
    }
    else
    {
       document.getElementById("newType").style.display = "none";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM