-1

I have code right now below that selects the value based on the selectedindex of 0 or since I only have two options. What I am trying to figure out is how to set the select value instead of by 0 or 1 by value like male or female

render() {
        setTimeout(() =>
          this.template.querySelector('[name="genderfield"]').selectedIndex = 1
        );
        
        return template;
    }

 <div class="nds-select_container">
            <select class="nds-select nds-has-value" name="genderfield" required onchange={handleChange}>
            <option value="male">Male</option>
            <option value="female">Female</option>
            </select>
            <label class="nds-form-element__label" for="select-01">Gender</label>
           </div>
1

You can use the HTMLSelectElement.options property of the select element to determine which item you want to select dynamically:

const genderfield = this.template.querySelector('[name="genderfield"]');
genderfield.selectedIndex = [...genderfield.options].findIndex(option => option.value === 'Female');
2
  • The following is getting a couple of errors, 1 where { is expected in the const genderfield line and another declaration or expected statement to end at the last ); I am not sure why 'render() { setTimeout(() => const genderfield = this.template.querySelector('[name="genderfield"]'); genderfield.selectedIndex = [...genderfield.options].findIndex(option => option.value === 'female'); //this.template.querySelector('[name="genderfield"]').selectedIndex = 1 ); return template; }'
    – Drake
    Jul 12 at 16:13
  • 1
    @DrakeDavenport If you have more than one line/statement in an arrow function, you need to write it as a function body, such as: setTimeout(() => { const genderfield = this.template.querySelector('[name="genderfield"]'); genderfield.selectedIndex = [...genderfield.options].findIndex(option => option.value === 'Female'); })
    – sfdcfox
    Jul 12 at 16:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.