'JS - Expected a conditional expression and instead saw an assignment [closed]

The piece of code below seems to work in online code editors but when using on Cloud9 IDE, it comes up with that error message. Is there a way to sort this or alternatively write this bit of code?

The error appears on line 3, the for loop statement.

var text1 = document.querySelector('input[name="contract-type"]').value;
var select1 = document.getElementById('contract-type-list');
for(var i, j=0; i = select1.options[j]; j++){
    if(i.text == text1){
        select1.selectedIndex = j;
        break;
    }
}


Solution 1:[1]

The linter is warning you that i = select1.options[j] is a strange expression to be checking for truthyness, because it's an assignment. While you could ignore the rule, a better approach would be to iterate through the option children from querySelectorAll or .children or with the collection's iterator instead of going through .options[index].

var text1 = document.querySelector('input[name="contract-type"]').value;
var select1 = document.getElementById('contract-type-list');
for (const [i, option] of [...select1.options].entries()) {
    if (option.text == text1) {
        select1.selectedIndex = i;
        break;
    }
}

Or, if the value is definitely one of the options, just do

document.getElementById('contract-type-list').value = document.querySelector('input[name="contract-type"]').value;

or, if it might not exist:

const inputText = document.querySelector('input[name="contract-type"]').value;
const select = document.getElementById('contract-type-list');
const matchingOption = [...select.children].find(option => option.text === inputText);
if (matchingOption) {
    select.value = matchingOption.ariaValueMax;
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 CertainPerformance