How to select a random value from a drop-down list in TruClient without selecting the first value.

  • KM01575335
  • 18-May-2015
  • 18-May-2015

Summary

TruClient allows you to automatically select a random value from a drop-down list by using 0 as step Ordinal. What if you need to prevent the first value from being selected?

Question

TruClient allows you to automatically select a random value from a drop-down list by using 0 as step Ordinal. How to avoid selecting the first value?

Answer

TruClient allows you to automatically select a random value from a drop-down list. To do so:

  1. Leave the step 'Text' argument blank.
  2. Use 0 as a step 'Ordinal' argument.

In some cases, there are values that should not be selected, like the "Please select" value in the following example:

<select>
 <option value="">Please select...</option>
 <option value="volvo">Mazda</option>
 <option value="saab">Saab</option>
 <option value="opel">Opel</option>
</select>


If 0 is used as a step 'Ordinal' argument, TruClient will select any of the 4 values, as they are all valid.
To prevent selecting the first option, the following workaround could be used:

  1. Leave the step 'Text' argument blank
  2. Use the following JavaScript code as a step 'Ordinal' argument (Make sure to change the Ordinal type to 'JS' and not 'Plain'):

Math.floor(Math.random() * (object.options.length - 1) + 2);

The above code will return a random number between 2 and the total number of elements in the list.
Note, that the Ordinal value of the first element in the list is 1, in contrast to the JavaScript index property where the first element's index would be 0.