RocketScienceGuy
RocketScienceGuy

Reputation: 161

Selecting Chosen options through javascript functions

I've been trying to implement a solution proposed in How do you select a particular option in a SELECT element in jQuery? to no avail. Either the addition of Chosen to the mix makes the solution invalid, or I've made some coding error that is beyond my compiler and me to find.

My html:

<select name="superType" class="chosen-select chosen-select-creation-allowed" id="superType" style="width: 300px; display: none;" onchange="loadInheritance()" multiple="">
  <option style="padding-left:20px;" value=""></option><option style="padding-left:0px" value="28">concept</option>
  <option style="padding-left:20px" value="30">human</option>
</select>

When I place the following after this, I expect one of them will add to the value="30" option above a 'selected' attribute:

      //$('#superType option[value="30"]').prop('selected', true);
        $('#superType option[value="30"]').attr('selected', 'selected');
        $('.chosen-select').trigger("chosen:updated");

Instead, nothing happens as according to the DOM model inspector and visual presentation.

What I want is to have this selection happen inside a function, but when I try to build the reference to the option above I get the error:

Syntax error, unrecognized expression: '#superType option[value="30"]'

Here is the javascript generating that (procs on 'cid'):

            //now go back through and select the ones this CommonNoun already had from before
            $.ajax({
                url: '/BackToTech/server?function=getExistingSuperTypes',
                type: 'POST',
                success: function (response){
    //              var target = $("#superType");           
                    var target = "#superType";          
                    selectOptions(response, target, 0);
                    $('.chosen-select').trigger("chosen:updated");
                }
            });

...

function selectOptions(obj, target) {
    var concepts = obj; 
    $.each(concepts, function(concept, value) {  
        alert(concept, value);
        if (concept == "cid") {
            optionValue = obj[concept].oid;
            $("'" + target + " option[value=\"" + optionValue + "\"]'").attr('selected', 'selected');
        } else { 
            selectOptions(value, target);
        }
    });
} 

Upvotes: 0

Views: 122

Answers (1)

user120242
user120242

Reputation: 15268

You don't need the single quotes around the css selector.

$(`${target} option[value="${optionValue}"]`).attr('selected', 'selected');

Upvotes: 1

Related Questions