Reputation: 41
Is there any way to select the first option having Value1 using css selector. I'm working on an automation tool created using puppeteer, I'm able to open the dropdown, but can't click on the options.
<select title="Visibility">
<option>Value1</option>
<option>Value2</option>
<option>Value3</option>
<option>Value4</option>
</select>
I have tried using this, but it didn't work
{
type: "navigation",
interaction: "click",
selector: 'select[title="Visibility"]',
script: (element) => {
element.selectedIndex = 0;
element.dispatchEvent(new Event('change'));
},
log: {
info: "Choosing Job Card Invoice Details",
},
}
Upvotes: 1
Views: 29
Reputation: 48713
If the <option>
elements don't have a value
attribute then the value will be defaulted to the text.
Each
<option>
element should have avalue
attribute containing the data value to submit to the server when that option is selected. If no value attribute is included, thevalue
defaults to the text contained inside the element. ~ MDN
You should be able to achieve this by setting the value
to the text of the item you want to select:
element.value = 'Value3';
element.dispatchEvent(new Event('change'));
Here it is in action:
const element = document.querySelector('select[title="Visibility"]');
// Listener
element.addEventListener('change', (e) => {
console.log(`Value changed to: ${e.target.value}`);
});
// Set value and fire the 'change' event
element.value = 'Value3';
element.dispatchEvent(new Event('change'));
<select title="Visibility">
<option>Value1</option>
<option>Value2</option>
<option>Value3</option>
<option>Value4</option>
</select>
Note: If you are responsible for that HTML, I would consider adding value
attributes.
Upvotes: 0