简体   繁体   中英

Show/ hide div depending on dropdown selection using pure javascript - no jquery

I want to know how to show/hide a div depending on dropdown selection using pure Javascript - without jQuery. I have already got it working in jQuery but my client doesn't want to use jQuery so I need to know how to make it using pure Javascript.

Check this fiddle for the working jQuery version http://jsfiddle.net/gB4hk/

This is my html

<select name="b_company" id="b_company">
    <option value="0" selected="selected">Individual</option>
    <option value="1">Company</option>
</select>

<div class="control-group" id="vat" style="display:none;">
    <label class="control-label" for="vatnumber">V.A.T. Number</label>
    <div class="controls">
        <input id="s_vatnumber" type="text" name="s_vatnumber" value="" />
    </div>
</div>

and this is what used to make it work in jQuery:

$(document).ready(function () {
    $('#b_company').on('change', function () {
        if (this.value == 1) {
            $("#vat").show();
        } else {
            $("#vat").hide();
        }
    }).change();
});

I need to know how to get the same result but using pure Javascript without jQuery.

demo jQuery version : http://jsfiddle.net/gB4hk/

like this http://jsfiddle.net/gB4hk/2/

<select name="b_company" id="b_company" onchange="showHideInput(this)">
    <option value="0" selected="selected">Individual</option>
    <option value="1">Company</option>
</select>

and

function showHideInput(sel) {
    var value = sel.value;  
    if(value==0)
        document.getElementById('vat').style.display = 'none';
    if(value==1)
        document.getElementById('vat').style.display = 'block';
};

As from the comments posted above

below is the working code

 window.onload = function () {
    document.getElementById('b_company').addEventListener('change', function () {
        if (this.value == 1) {
            document.getElementById('vat').style.display = 'block';
        } else {
            document.getElementById('vat').style.display = 'none';
        }
    }, false)
};

Demo Hope this helps...

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