user971741
user971741

Reputation:

Selecting an option with given value

I am trying to select a particular option from a select list depending on the value, I have following markup:

<select name="class" id="class">
    <option value="1">679460ED-0B15-4ED9-B3C8-A8C276DF1C82</option>
    <option value="2">B99BF873-7DF0-4E7F-95FF-3F1FD1A26139</option>
    <option value="3">1DCD5AD7-F57C-414</option>
    <option value="4">6B0170AA-F044-4F9C-8BB8-31A51E452CE4</option>
    <option value="5">C6A8B</option>
    <option value="6">1BBD6FA4-335A-4D8F-8681-DFED317B8052</option>
    <option value="7">727D71AB-F7D1-4B83-9D6D-6BEEAAB</option>
    <option value="8">BC4DE8A2-C864-4C7C-B83C-EE2450AF11B1</option>
    <option value="9">AIR CONDITIONING  SYSTEM</option>
    <option value="10">POWER GENERATION SYSTEM</option>
</select>

<script>
    selectThisValue('#class',3);
</script>

in .js

function selectThisValue(element,value) {
    console.log(value); 
    var elem = $(element + ' option[value=' + value + ']');
    console.log(elem);
    elem.attr("selected", "selected");
}

Results for console.log are as follows:

3

[prevObject: i.fn.i.init[1], context: document, selector: "#class option[value=3]", jquery: "1.10.2", constructor: function…]

But this is not working, no errors are given but nothing happens also. Please help identifying the where am I wrong.

Upvotes: 0

Views: 99

Answers (3)

Ja͢ck
Ja͢ck

Reputation: 173522

Simple:

$('#class').val('3');

Or use the index of the option (if you know it):

$('#class').prop('selectedIndex', 2);

Upvotes: 0

Mika Tuupola
Mika Tuupola

Reputation: 20377

You can set the selected option just by calling $.val().

$("#class").val(3);

Working example at: http://jsfiddle.net/QphFX/

Upvotes: 0

sjmog
sjmog

Reputation: 161

This would be a nicer solution to your problem, since you are already using jQuery:

$("#class")[0].selectedIndex = 0 //or whichever index you want selected

Upvotes: 0

Related Questions