gunwin
gunwin

Reputation: 4832

Jquery changing the value of a drop-down using its value, not the text

I'm having difficulty changing the calue of a dropdown menu using jquery.

<div class="input-box">
    <select name="options[4]" id="select_4">
    <option value="">-- Please Select --</option>
    <option value="24">Not Sure - Send Me Some Samples First </option>
    <option value="13">1 Jet Black </option>
    <option value="14">Blondette 4/27 </option>
    <option value="15">Boho Blonde 613/12 </option>
    <option value="16">Caramel 6 </option>
    <option value="17">Cherry 530 </option>
    <option value="18">Dirty Blonde 612/12 </option>
    <option value="19">Ebony Black 1b </option>
    <option value="20">Hot Toffee 4 </option>
    <option value="21">LA Blond 24/613 </option>
    <option value="22">Malibu Blonde 60/613 </option>
    <option value="23">Raven 2 </option></select>
</div>

I can't understand why this won't work

function changeIt(theId) {
    $j('.input-box:eq(0)').val(theId);
}

changeIt(22);

Upvotes: 2

Views: 651

Answers (3)

gunwin
gunwin

Reputation: 4832

I figured it out. This loops through the first SELECT contained in the div with '.input-box' class. Pulling out the ID and the text.

$j('.input-box:eq(0) option').each(function() {

    theText=$j(this).text();
    itsId = $j(this).val();      

});

I used this to pull out all the values and generate buttons depending on the drop-downs current options. Then i used the folloqing function (onClick) to change the selected value of the drop-down.

function changeOption(theId) {
    //alert("Change to value number:"+theId);
    $j('.input-box select').val(theId); 
}

Upvotes: 0

karim79
karim79

Reputation: 342635

Try:

$j('.input-box:first select > option[value=' + theId + ']').attr('selected', 'selected');

Upvotes: 1

Felix Kling
Felix Kling

Reputation: 816334

Well, you are not selecting the select element:

$j('.input-box:eq(0) select').val(theId);

'.input-box:eq(0)' only selects the div. And the val() method has no effect on divs.

DEMO

Upvotes: 3

Related Questions