javascriptjquery

How go through option in select?


How to go through options of an HTML select element?

I tried the following, but I get an error.

Here is the code:

const valInput = modalBody.querySelector('#conditionValue');

if (valInput ) {
    for (let i = 0; i < valInput.options.length; i++) {
        if (valInput.options[i]) {
            const option = valInput.options[i];
        }
        option.className = option.value;
        const optionClass = option.className;
        const optionValue = option.value;

        console.log(` Class: : ${optionClass}`)
        console.log(` Value: : ${optionValue}`)
    }
}

The error occurs right after the if statement:

Reference Error: option is not defined


Solution

  • When you define a const within a statement block, like in an if block, its scope is restricted to it:

    if (valInput.options[i]) {
        const option = valInput.options[i];
    }
    

    You cannot access that variable option outside that block, like you do in this statement:

    option.className = option.value;
    

    ...which gives a Reference Error ("option is not defined").

    Taking a step back, that if condition is always going to be true, so just move the const declaration out of it, and get rid of the now empty if statement. That will solve the issue.

    Unrelated, but JavaScript offers the for..of loop syntax, where you don't need an index variable like i anymore. It would look like this in your case:

    for (const option of valInput.options) {
        // your code that deals with option
    }