Search code examples
javascriptjqueryjquery-selectors

JS - compare select option then make it selected


We have several <select> fields that need to be set at the specified <option>. We have this "answer list" with UUID. Every <option> is evaluated: if the UUID is included at "answer list" then thats the <option> selected, otherwise we keep default "not available" <option> selected.

See below my current code, the comparison is the part I'm facing trouble.

JS code:

$('#severalStores .selectLimitInformation').each(function () { //Scan all the select fields        
    $(this).find("option").each(function () { //Search within every option            
        $.each(JSON.parse(answerList), function (item) { //Scan all "answer list"

            //Compare values then choose value (not working)
            if ($(this).option.value == item.expectedUUID)
                $(this).val(item.expectedUUID);
            else
                $(this).val('0');
            $(this).trigger('change');
        });
    });
});

HTML code:

<div class="row form-horizontal" id="severalStores">
    <div class="col-md-6">
        <div class="row form-horizontal">
            <div class="col-md-4">
                <label>Store AAA:</label>
            </div>
            <div class="col-md-8">
                <select class="form-control selectLimitInformation">
                    @foreach (...) //data from ViewBag
                    {
                        <option value="@storeLimit.info">@storeLimit.description</option>
                    }
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        <div class="row form-horizontal">
            <div class="col-md-4">
                <label>Store BBB:</label>
            </div>
            <div class="col-md-8">
                <select class="form-control selectLimitInformation">
                    @foreach (...) //data from ViewBag
                    {
                        <option value="@storeLimit.info">@storeLimit.description</option>
                    }
                    <option value="0">Not available</option>
                </select>
            </div>
        </div>
        //Several other select
    </div>
</div>

Solution

  • You don't need the nested loops. Put all the expected UUIDs in a Set. Then you can use the .has() method to test if the option value is in the set, and update the select value.

    answerList = JSON.parse(answerList);
    let expectedUUIDs = new Set(answerList.map(a => a.expectedUUID));
    $('#severalStores .selectLimitInformation').each(function(i, select) { //Scan all the select fields    
      select.value = "0"; // start with a default    
      $(this).find("option").each(function(j, option) { //Search within every option      
        if (expectedUUIDs.has(option.value)) {
          select.value = option.value;
          return false; // stop looping over the options
        }
      });
    });