What is the best way to select a random item from a DropDownList using JavaScript?

I am looking to automate the process of selecting random items from a dropdown list. Currently, it is selecting items in order from first to last, but I would like it to select items randomly.

/* function to automatically select items from DropDownList1 */
function selectFromDropdown(selector, text) {
  $(selector).find('option').each(function() {
    if ($(this).text() == text) {
      $(selector).val($(this).val());
      return false;
    }
  })
}

$(document).ready(function() {
  let numberOfTimes = 0;
  const time = 1000 //3s
  let values = [];
  $('#DropDownList1').find('option').each(function() {
    values.push($(this).text())
  });
  console.log(values);
  const interval = setInterval(function() {
      selectFromDropdown('#DropDownList1', values[numberOfTimes])
      if (numberOfTimes == values.length - 1) {
        clearInterval(interval);
      } else {
        numberOfTimes = numberOfTimes + 1;
      }
    },
    time);
});

To see the code in action, visit: https://jsfiddle.net/lucasangelo_/17Lgr0kc/6/

Answer №1

If you're looking to retrieve random values from a dropdown selection, you can make use of the following function:

function fetchRandomValuesFromDropdown(selector, amount)
{
    var chosenValues = [];
    var dropdownChildren = document.getElementById(selector).children;

    for (var i = 0; i < amount; i++) {
        var randomNumber = Math.floor(Math.random() * dropdownChildren.length);
        var randomOptionChosen = dropdownChildren[randomNumber];

        if (chosenValues.indexOf(randomOptionChosen.value) < 0) {
            chosenValues.push(randomOptionChosen.value);
        } else {
            i--;
        }
    }

    return chosenValues;
}

You can then invoke it as follows:

fetchRandomValuesFromDropdown("DropDownList1", 3);

Answer №2

The solution has been provided:

  /* utility function to automatically choose options from a dropdown list */
    function pickItemFromDropdown(selector, text) {
      $(selector).find('option').each(function() {
        if ($(this).text() == text) {
          $(selector).val($(this).val());
          return false;
        }
      })
    }

    function generateRandomNumber(min, max) {
      return (Math.random() * (max - min) + min).toFixed(0);
    }

    $(document).ready(function() {
      let counter = 0;
      const timeBetweenCalls = 1000 //3s
      let values = [];
      $('#DropDownList1').find('option').each(function() {
        values.push($(this).text())
      });
      console.log(values);

      const interval = setInterval(function() {
          const randomNumber = generateRandomNumber(0, values.length - 1);
          const randomItem = values[randomNumber];
          //console.log(randomItem);
          pickItemFromDropdown('#DropDownList1', randomItem),
            console.log(`${counter} - Made a PostBack call for ${randomItem}`);
          //__doPostBack('LButton3', 'OnClick');
          if (counter == values.length - 1) {
            console.log("Iterated through all items, clear the setInterval");
            clearInterval(interval);
          } else {
            counter = counter + 1;
          }
        },
        timeBetweenCalls);
    });

Appreciate your help!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the Ng2-Charts Linechart to display all values instead of just the first two

Starting a new Angular application with the Angular-CLI (beta 22.1) has presented an issue when adding test data (5 values) to a chart. The scaling appears incorrect, displaying only the first two values stretched across the entire length of the graph (ref ...

Decoding the file's encoding: A beginner's guide

I need help determining the encoding of a file in order to only upload CSV files with utf-8 format. If there are any non utf-8 characters, I want to display an error message. Currently, I am utilizing Papa Parser for parsing. Is there a way to detect the ...

The persistent issue of the modal box disappearing persists, despite my efforts to remove additional instances of bootstrap.min

I have been struggling to prevent my modal box from disappearing, despite trying various solutions found online. How can I ensure that it stays visible? Here is the code in question: <html> <head> <title> Test Slides </titl ...

Tips for maintaining server session by tracking user activity on the browser using a simple ajax request to the server without relying on JQuery

In my website, the server session Timeout is set to 30 minutes. <system.web> <sessionState timeout="30" /> </system.web> However, if a user is actively engaging with the site by typing a long comment or selecting chec ...

Troubleshooting the "Failed to mount component" error in Vue: fixing template or render function definition issues

Struggling with writing a Vue component, encountering the issue: Failed to mount component: template or render function not defined. Tried various fixes like adding default when importing the component, but none of them seem to work. My component code is i ...

Tips for managing promise rejection when generating a highland stream from a promise?

When working with [email protected] and [email protected] via typescript, the following code snippet is utilized: import * as highland from "highland"; import * as lodash from "lodash/fp"; const range = lodash.range(0, 10); const createPromise ...

What could be causing the lack of responsiveness on this page?

I have created a webpage with over 1100 lines of code using JSF 2.0. The page is filled with PrimeFaces components and I have implemented JQuery to control the appearance and disappearance of these components. The webpage functions smoothly on Firefox 4.0 ...

Guide to authoring stored procedure updates in webmatrix format?

I have successfully written an update query in my webmatrix form, but now I want to replace it with a stored procedure. How can I do that? var UpdateQuery = "UPDATE Reg_tb SET FirstName = @0, LastName = @1, UserName = @2, Password = @3 WHERE UID = @4"; ...

What is preventing the successful insertion of a JSON array into a SQL database?

I am facing an issue with inserting a JSON array into an SQL database. I have an HTML table that stores its data in a JavaScript array, converts it to a JSON array, and then sends it to a PHP file. However, when trying to insert this JSON array into the da ...

Preserving the top line or heading while cutting through a table

In my HTML, I have a table with the following structure: <table id="table"> <tr> <td>ID</td> <td>Place</td> <td>Population</td> </t ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Picturing a way to paint a displaced bar within an ASP.NET Chart

I am currently using System.Web.UI.DataVisualization.Charting.Chart functionality to create displaced bars within my chart. I would like the bars to start at point 1 and be shifted 55 pixels to the right for a more distinct visual appearance. The desired ...

Unable to locate the name 'Cheerio' in the @types/enzyme/index.d.t file

When I try to run my Node application, I encounter the following error: C:/Me/MyApp/node_modules/@types/enzyme/index.d.ts (351,15): Cannot find name 'Cheerio'. I found a suggestion in a forum that recommends using cheerio instead of Cheerio. H ...

What is the best way to ensure that my multiple choice code in CSS & JS only allows for the selection of one option at a time? Currently, I am able

I'm currently facing a small issue that I believe has a simple solution. My knowledge of Javascript is limited, but I am eager to improve my skills in coding for more visually appealing websites. My problem lies in the code snippet below, where I am ...

Despite the use of v-if and v-else directives in Vue 2, a specific component properties are not being updated while the others are updating

Vue2 is not updating one specific component (<Button>) inside v-if and v-else, while the rest of the content is updated. I have recently discovered a solution to make this code function, but I am still unsure about Vue2 re-rendering behavior. I worr ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

Explore Youtube to find the most popular video IDs

Is it possible for me to use a string to search YouTube and retrieve the id for the top video in the search results? I want to be able to play that video directly on my website. All I have is the URL for the search: youtube_url/results?search_query=thevid ...

Loading data into a Dojo ItemFileReadStore using Grails and the "render as JSON" method

I have developed a controller method that generates a JSON "file" on-the-fly when the corresponding URL is accessed. This file exists in memory and not saved on disk, as it's dynamically created when the URL is hit. I'm attempting to utilize this ...

The issue of video tags not displaying previews on iPhone across all browsers is also accompanied by problems with controls not functioning correctly

As I delve into the world of HTML5 video tags, I encountered an issue where the video wouldn't show a preview frame initially. Instead, only the Resume button would appear. Furthermore, after playing the video with the Resume button, it wouldn't ...

Guide to implementing nested asynchronous calls using a foreach loop

I am eager to enhance my skills and gain a better understanding of how to improve this code. While the current code is functioning, I suspect there may be an issue that needs addressing. Here's the concept: 1: Initially, I send the first HTTP request ...