-1

Not had much experience of javascript, or nightwatch.js so apologies if this seems an obvious thing to do.

I have a dropdown menu that gets randomly populated.

What I'd like to do is randomly select one of these dropdown menu options.

The html for the drop-down menu is as follows;

enter image description here

And I'd like to select just one entry from the list (which of course would change - including the number of entries and names - the next time the element is loaded).

I have a working ruby script;

modelrangeselect = @driver.find_element(:id, 'listRange_ddlItems')
carmodelrange = modelrangeselect.find_elements(:tag_name => 
'option').sample

But I just can't work out what the javascript equivalent would be so I can run it on nightwatch.js.

Any help would be really appreciated.

Thanks.

Darren Harley
  • 75
  • 1
  • 18

1 Answers1

1

In my opinion this should be enough to select one of the options at random, The code should be self explanatory :).

 // get the dropdown element
 const select  = document.getElementsByClassName('url-dropdown');

 // fetch all options within the dropdown
 const options = select.children;  

 // generate a random number between 0 and the total amount of options
 // the number will always be an index within the bounds of the array (options) 
 const random  = Math.floor(Math.random() * options.length);

 // set the value of the dropdown to a random option
 select.value = options[random].value; 
Bargros
  • 521
  • 6
  • 18
  • Thanks for the speedy response Bargros. However, when I run the test using your code above I get the following error; **✖ TypeError: Cannot read property 'length' of undefined** Any ideas why I'm getting this error? Thanks – Darren Harley Sep 04 '18 at 11:12
  • you might be running the script before the ` – Bargros Sep 04 '18 at 13:22