简体   繁体   中英

jQuery show/hide div with select options by name

I am having problem with showing/hiding my divs, which depent on selected value "name".

Here is my HTML :

    <select name="selectVehicle" id="selectVehicle">
    <option name="A" value="A">Car</option>
    <option name="C" value="C">Truck</option>
    </select>
    <div id="A" class="vehicle">+Car+</div>
    <div id="C" class="vehicle" style="display:none;">+Truck+</div>

...And my JS:

    $(function() {
        $('#selectVehicle').change(function(){
            $('.vehicle').hide();
            $('#' + $(this).val()).show();
        });
    });

https://jsfiddle.net/wgee7ekh/1/

Here is how you select based on the name attribute:

$(function() {
    $('#selectVehicle').change(function(){
        $('.vehicle').hide();
        $('#' + $(this).find('option:selected').attr('name')).show();
    });
});

Here's a JSFiddle

You can use :selected to get the name property of selected option.

$('#selectVehicle').change(function(){
    $('.vehicle').hide();
    $('#' + $(':selected',this).attr('name')).show();
});

Updated Fiddle

The issue is that this in your .change() event handler is the <select> element, not the selected <option> element, but you want the name attribute from the selected <option> element.

You can get the selected option in a couple ways. In plain Javascript, you can use the .options array and the .selectedIndex property as in this.options[this.selectedIndex] to get it like this:

$(function() {
    $('#selectVehicle').change(function(){
        $('.vehicle').hide();
        $('#' + this.options[this.selectedIndex].getAttribute("name")).show();
    });
});

jsFiddle: https://jsfiddle.net/jfriend00/upswtfeg/

or in jQuery, you can use the pseudo-selector :selected to find it like this:

$(function() {
    $('#selectVehicle').change(function(){
        $('.vehicle').hide();
        $('#' + $(this).find('option:selected').attr('name')).show();
    });
});

jsFiddle: https://jsfiddle.net/jfriend00/ywkd25w8/

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