Denoteone
Denoteone

Reputation: 4055

Can not figure out why my Select Dropdown only updates once

I am using JQuery to update the defualt option of a select dropdown based on the value of another select dropdown. For some reason the update only works on the first change and I can not figure out why.

HTML:

<label>Enclosure Type:</label>
<select name="enclosure_type_it">
    <option value="global">Global </option>
    <option value="server_optimized">Server Optimized </option>
</select>
<div class="pure-control-group">
    <label>Handles:</label>
    <select name="handles_it" id="handles_datacenter">
        <option value="Semi Cylinder">Semi Cylinder</option>
        <option value="Combo_Security Handle">Combo/Security Handle </option>
        <option value="Comfort Handle">Comfort Handle </option>
    </select>
</div>
<div class="pure-control-group">
    <label>Inserts:</label>
    <select name="inserts_it" id="inserts_datacenter">
        <option value="Pushbutton">Pushbutton </option>
        <option value="Locking pushbutton">Locking pushbutton </option>
        <option value="Locking">Locking </option>
    </select>
</div>

JQuery:

$('#enclosure_type_it').change(function() {
    if ($(this).val() == "global") {
        $('#handles_datacenter option[value="Semi Cylinder"]').attr("selected", true);
        $('#inserts_datacenter option[value="Locking"]').attr("selected", true);
    }
    if ($(this).val() == "server_optimized") {
        $('#handles_datacenter option[value="Comfort Handle"]').attr("selected", true);
        $('#inserts_datacenter option[value="Locking pushbutton"]').attr("selected", true);
    }
}).change();

Still not sure what I am doing wrong: http://jsfiddle.net/y7easnb7/

Upvotes: 0

Views: 40

Answers (1)

Satpal
Satpal

Reputation: 133403

Use .val() to set value also you need to use enclosure_type_it as ID of select.

HTML

<select id="enclosure_type_it">

Script

$('#enclosure_type_it').change(function() {
    if ($(this).val() == "global") {
        $('#handles_datacenter').val("Semi Cylinder");
        $('#inserts_datacenter').val("Locking");
    }
    if ($(this).val() == "server_optimized") {
        $('#handles_datacenter').val("Comfort Handle");
        $('#inserts_datacenter').val("Locking pushbutton");
    }
}).change();

If you want to use name attribute. Use following as selector

$('select[name="enclosure_type_it"]')

Upvotes: 3

Related Questions