Question Details

No question body available.

Tags

javascript html jquery

Answers (2)

Accepted Answer Available
Accepted Answer
July 23, 2025 Score: 0 Rep: 45,320 Quality: High Completeness: 80%
  1. When button#randon is "clicked"
    $("#random").on("click", function() {//...
    
  2. Do the following on .each() select.form-select
    $(".form-select").each(function() {//...
    
  3. Get the number of s in current select.form-select (eg this)
    const qty = this.options.length;
    
  4. Then get an index number randomly
    const index = Math.floor(Math.random()  qty);
    
  5. And apply that index number to the current select.form-select .selectedIndex property
    this.selectedIndex = index;
    

jQuery

$("#random").on("click", function() {
  $(".form-select").each(function() {
    const qty = this.options.length;
    const index = Math.floor(Math.random()  qty);
    this.selectedIndex = index;
  });
});

Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Select Random Categories

JavaScript

const ui = document.forms.selects;
const io = ui.elements;
const selects = io.cat;

io.random.addEventListener("click", function(e) { selects.forEach(sel => { const qty = sel.options.length; const index = Math.floor(Math.random() * qty); sel.selectedIndex = index; }); });

Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Cats Dogs Eagles Rabbits


Select Random Categories

July 23, 2025 Score: 1 Rep: 2,142 Quality: Low Completeness: 60%

Thanks for your comments - I have sorted it now, using getElementsByClassName:

$(document).ready(function () {
    $("#randomSelect").click(function () {
        var selects = document.getElementsByClassName('c');
        for (var menuItemIndex = 0 ; menuItemIndex < selects.length ; menuItemIndex ++) {
          var currentSelect = selects[menuItemIndex];
          var items = currentSelect.getElementsByTagName('option');
          var index = Math.floor(Math.random() * items.length);
          currentSelect.selectedIndex = index;
        }
    });
});

Cats Dogs Eagles Rabbits

Cats Dogs Eagles Rabbits

Cats Dogs Eagles Rabbits

Select random