Select option base on property key in value

<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?

Answers 1

  • 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.


    // 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 === 123;
    }).prop('selected', true); // Set the option as selected
    <script src=""></script>
        <option value="Hello">fdsafds</option>
        <option value='{"name":"abc","id":123}'>abc</option>

    As Rayon has commented, instead of using object as the value, I'll recommend to use HTML5 data-* custom attributes to store data on element.

    $('option[data-id="123"]').prop('selected', true);
    <script src=""></script>
        <option value="Hello" data-name="bond" data-id="007">fdsafds</option>
        <option value="something" data-name="abc" data-id="123">abc</option>

Related Articles