Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

<option value="abc">abc</option>

I know I can do $('select').val('abc') but what if I have something like this

<option value='{"name":abc,"id":123}'>abc</option>

How do I select abc base on id?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
426 views
Welcome To Ask or Share your Answers For Others

1 Answer

The value is not a valid Object. abc should be wrapped in quotes.

The <option> should be

<option value='{"name":"abc","id":123}'>abc</option>
                       ^   ^

You can use filter() to filter out the <option> elements which are having the id as 123 in the value attribute object-like string.

Then, prop('selected', true) can be used on the filtered option to set as selected option.

Demo:

// Filtering all options in the select
$('select option').filter(function() {
    var val = $(this).val(), // Get value
        obj = {};

    // Try to parse the string to JSON
    try {
        obj = JSON.parse(val);
    } catch (e) {
        obj = {}; // Empty object if parsing fails
    }

    // Filter based on the `id` in the value
    return obj.id === 123;
}).prop('selected', true); // Set the option as selected
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<select>
    <option value="Hello">fdsafds</option>
    <option value='{"name":"abc","id":123}'>abc</option>
</select>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...