Paul Vincent Paul Vincent - 2 months ago 16
HTML Question

Default value in dropdown menu (JavaScript)

I wish to set the default value in a dropdown menu to the middle one (not the first).

I use dropdowns on my site for visitors to choose one of three / four / five sizes of a product.

The JavaScript is:

$(document).ready(function () {
$('.group').hide();
$('#option1').show();
$('#selectMe').change(function () {
$('.group').hide();
$('#'+$(this).val()).show();
})
});


The other code is:

<select id="selectMe">
<option value="option1">S</option>
<option value="option2">M</option>
<option value="option3">L</option>
</select>


User chooses a value, and then the BUY button changes accordingly. Thus ...

<div>
<div id="option1" class="group">Button for size S</div>
<div id="option2" class="group">Button for size M</div>
<div id="option3" class="group">Button for size L</div>
</div>


This works great, but in this instance, I want M to be the default, and not S (there are three sizes here, but sometimes there are more).

Answer

Just use following snippets:

  1. With jQuery

    $(document).ready(function () {
        var $select = $('#selectMe');
    
        $select.val("option2");//initial value
        $("[id=" + $select.val() + "]").show()
            .siblings().hide();
    
        $select.change(function () {
            $("[id=" + $select.val() + "]").show()
                .siblings().hide();
        });
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <select id="selectMe">
            <option value="option1">S</option>
            <option value="option2">M</option>
            <option value="option3">L</option>
        </select>
    
        <div>
            <div id="option1" class="group">Button for size S</div>
            <div id="option2" class="group">Button for size M</div>
            <div id="option3" class="group">Button for size L</div>
        </div>

  2. Or, You can do it through pure JavaScript

    var selectBox = document.getElementById("selectMe")
    selectBox.selectedIndex = parseInt(selectBox.length / 2);
    
    selectBox.onchange = function () {
        changeButton(this.value);
    }
    
    changeButton(selectBox.value);
    
    function changeButton(val) {
        console.log(val)
        var i = -1, elements = document.querySelectorAll('[class=group]');
        while (elements[++i]) {
            console.log(elements[i]);
            elements[i].style.display = (elements[i].id == val) ? "block" : "none";
        }
    }
    <select id="selectMe">
        <option value="option1">S</option>
        <option value="option2">M</option>
        <option value="option3">L</option>
    </select>
    
    <div>
        <div id="option1" class="group">Button for size S</div>
        <div id="option2" class="group">Button for size M</div>
        <div id="option3" class="group">Button for size L</div>
    </div>