Consolidate code by implementing on selectmenu

I need assistance with handling multiple select menus on a View page

Below is a snippet of the code:

$(function() {
  var selectSpeed = $('#speed'),
    selectTest = $('#test');

  selectSpeed.selectmenu();
  selectTest.selectmenu();

  $("#speed-button").on("mousedown", function() {
    selectSpeed.selectmenu("open");
  });
  $('#speed-button').on("click", function() {
    selectSpeed.selectmenu("open");
  });

  $(document).on("mouseup", "#speed-menu .ui-menu-item-wrapper", function() {
    selectSpeed.val($(this).text().substr(0, 1)).change();
    selectSpeed.selectmenu("close");
    selectSpeed.selectmenu("refresh");
  });

  
  $("#test-button").on("mousedown", function() {
    selectTest.selectmenu("open");
  });
  $('#test-button').on("click", function() {
    selectTest.selectmenu("open");
  });

  $(document).on("mouseup", "#test-menu .ui-menu-item-wrapper", function() {
    selectTest.val($(this).text().substr(0, 1)).change();
    selectTest.selectmenu("close");
    selectTest.selectmenu("refresh");
  });
});
fieldset {
  border: 0;
}

label {
  display: block;
  margin: 30px 0 0 0;
}

.overflow {
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="demo">
  <form action="#">
    <fieldset>
      <select name="speed" id="speed">
        <option selected="selected" value="1">1 adult</option>
        <option value="2">2 adults</option>
        <option value="3">3 adults</option>
        <option value="4">4 adults</option>
        <option value="5">5 adults</option>
        <option value="6">6 adults</option>
        <option value="7">7 adults</option>
        <option value="8">8 adults</option>
        <option value="9">9 adults</option>
      </select>
      <select name="test" id="test">
        <option selected="selected" value="1">1 test</option>
        <option value="2">2 test</option>
        <option value="3">3 test</option>
        <option value="4">4 test</option>
        <option value="5">5 test</option>
        <option value="6">6 test</option>
        <option value="7">7 test</option>
        <option value="8">8 test</option>
        <option value="9">9 test</option>
      </select>
    </fieldset>
  </form>
</div>

Functionality of this code:

When I click on a span, it triggers the selectmenu to open. While still holding the mouse button down, I can move to a select field value (e.g., 2 adults in the first selectmenu) and release the mouse button to update the span accordingly.

Required Action:

For each new field, I have to define a new variable like var selectAnyone = $('#anyone'), apply .selectmenu() to it, and then create a new event listener with $(document).on("mouseup",, and repeat this process for every new field.

How can I streamline this code to handle all future fields in a unified way?

Answer №1

Here is a functional snippet that should align with your desired outcome.
I've streamlined the code to work with multiple select elements as needed...
Please ensure that each select has a unique id, matching the menu's id.

$(function() {

  // Loop through all selects in the form
  $('.demo form select').each(function(index, value) {

    var select_elm = $(this);
    var select_id = $(this).attr('id');
    $(select_elm).selectmenu();
    
    // Menu opening
    $("#" + select_id + "-button").on("mousedown click", function() {
      select_elm.selectmenu("open");
    });  

    // Option selection
    $(document).on("mouseup", ".ui-selectmenu-open .ui-menu-item-wrapper", function() {
      // Check for multiple menus
      if (
        (select_id + '-menu') ==                 // Name of the menu for this select_elm
        ($(this).closest('.ui-menu').attr('id')) // Name of the menu just clicked
      ) {
        $(select_elm).val($(this).text().substr(0, 1)).change();
        $(select_elm).selectmenu("close");
        $(select_elm).selectmenu("refresh");

        // Testing - verify only one value changes
        var test = '';
        $('.demo form select').each(function(index, value) {
          test += $(this).attr('id') + ': ' + $(this).val() + ',   ';
        });
        console.clear();
        console.log(test);

      }
    });

  });
});
fieldset {
  border: 0;
}

label {
  display: block;
  margin: 30px 0 0 0;
}

.overflow {
  height: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">

<div class="demo">
  <form action="#">
    <fieldset>
      <select name="speed" id="speed1">
        <option selected="selected" value="1">1 adult</option>
        <option value="2">2 adults</option>
        <option value="3">3 adults</option>
        <option value="4">4 adults</option>
        <option value="5">5 adults</option>
        <option value="6">6 adults</option>
        <option value="7">7 adults</option>
        <option value="8">8 adults</option>
        <option value="9">9 adults</option>
      </select>
      <select name="test" id="test1">
        <option selected="selected" value="1">1 test</option>
        <option value="2">2 test</option>
        <option value="3">3 test</option>
        <option value="4">4 test</option>
        <option value="5">5 test</option>
        <option value="6">6 test</option>
        <option value="7">7 test</option>
        <option value="8">8 test</option>
        <option value="9">9 test</option>
      </select>
    </fieldset>
    <fieldset>
      <select name="speed" id="speed2">
        <option selected="selected" value="1">1 adult</option>
        <option value="2">2 adults</option>
        <option value="3">3 adults</option>
        <option value="4">4 adults</option>
        <option value="5">5 adults</option>
        <option value="6">6 adults</option>
        <option value="7">7 adults</option>
        <option value="8">8 adults</option>
        <option value="9">9 adults</option>
      </select>
      <select name="test" id="test2">
        <option selected="selected" value="1">1 test</option>
        <option value="2">2 test</option>
        <option value="3">3 test</option>
        <option value="4">4 test</option>
        <option value="5">5 test</option>
        <option value="6">6 test</option>
        <option value="7">7 test</option>
        <option value="8">8 test</option>
        <option value="9">9 test</option>
      </select>
    </fieldset>
  </form>
</div>

I trust this provides value!

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

Steps for creating interconnected datepickers in jQuery with month and year selection:To create a dependent datepicker with month and year selection using

The JSFiddle I currently have is not functioning as expected. When the user directly selects the end-date, it does not restrict the start-date in this particular fiddle. It should change once the user directly changes the end-date. The functionality works ...

Issue in Opera with the $(window).load(function(){}); script

In order to display the body's main div height correctly after all content (images) have loaded, I utilized a combination of jQuery and CSS. //The CSS used is as follows body {display: none;} /* Function to calculate div block height */ function re ...

Storing a variable in jQuery using AJAX and retrieving it at a later time

Hey there! I'm currently using jQuery and AJAX to fetch the user ID of the logged-in user. I'm storing this information in a variable so that I can use it for some logic later on. However, I'm facing issues with accessing it. Here's my ...

Is there a way to invoke bootstrap 5 modals using JavaScript without the need for jQuery in the scripts?

Despite the existence of similar inquiries regarding this issue, I am determined to discover a solution that does not involve integrating jQuery into my scripts. Currently, I am encountering an error when attempting to invoke bootstrap 5 modals using JS. M ...

Use the accelerometer in JavaScript and Cordova to control the movement of an object, such as a ball

Having trouble figuring out how to move a ball using the accelerometer. Any tips on combining the accelerometer values with the ball movement? Waiting for accelerometer... <div id="heading">Waiting for heading...</div> <div id="ball" ...

What is the best way to implement CSS in this JavaScript Fetch code in order to manipulate the text's position and font style

Hello, I am just starting out with JS. Is there a way for me to customize the position and font of text in this JS Fetch function using CSS? Any help will be greatly appreciated. let file = 'art.txt'; const handleFetch = () => { fe ...

What's the reason my JavaScript isn't functioning properly?

Brand new to coding and I'm delving into the world of Javascript for the first time. In my code, there's a checkbox nestled within an HTML table (as shown below). <td><input type="checkbox" id="check1"/> <label th:text="${item.co ...

Difficulty in utilising jQuery to serialize HTML form

Hey there, I'm just starting out with ASP.NET development and I'm having trouble figuring out how to properly serialize a form using jQuery. Check out this screenshot for more details: https://i.stack.imgur.com/0UFLX.png <html xmlns="http://w ...

Tips for positioning the popup ul in relation to its parent li

How can the pop-up ul be positioned in the center of the parent li using CSS? * { margin: 0; padding: 0; } #track-nav { margin-left: 50px; margin-top: 50px; float: left; width: 100%; list-style: none; font-weight: bold; margin-bottom: ...

Achieving full coverage of cell content within a cell area by utilizing align-items in CSS Grid

Is it possible to achieve two conflicting goals using CSS Grid? In my design, I want the content in each cell to be vertically centered using align-items: center; At the same time, I need the entire area of the cell to be filled with color. However, ...

Nested loops in JavaScript can be combined with promises to efficiently handle

I am facing a challenge in looping through an array that contains another array as one of the parameters. My goal is to iterate through this nested array according to specific requirements, and then execute a function once the parent loop is finished. Can ...

Receiving POST data in the req.body object with only the key specified in Express.js

I am encountering an issue with my current POST request. There is a simple function in place that handles the sending of data to the server using AJAX. handleSubmit(event) { var http = new XMLHttpRequest(); // object allows for making http requests // ...

Ensuring the aspect ratio of images stays consistent within a flexbox using CSS

How can I create a grid of images without any spacing in between them? I want the width to be 100% of the parent element and each column to have the same size, for example, 20%. Using flex takes care of the columns, but I'm struggling with making the ...

Creating input fields in Vue 3: Best practices

I am looking to create an input field that automatically removes entered characters if they do not match a specific pattern. Here is the template: <input type="text" :value="val" @input="input" /> And here is the ...

Selecting a folder path with Angular 6: A step-by-step guide

Currently, I am aiming to extract the folder path string without uploading any files. The goal is simply to capture the path for future use. Below is an example of how you can prompt users to select a file: <input id="folder-input" #folderRef type="fil ...

In React using Flow Type, the syntax [...mySet] doesn't function as expected, while Array.from(mySet) successfully converts the

Why is it that with React and Flow Type, the line of code displaying [{}] when using JSON.stringify([...mySet]) but shows the correct values with JSON.stringify(Array.from(mySet))? The issue seems perplexing as this behavior cannot b ...

`How can I integrate jQuery UI using Webpack in my project?`

I recently initiated a fresh project utilizing React Slingshot and am experimenting with integrating jQuery UI accordions. I've included the jQuery UI plugin using NPM with the command npm install --save jquery-ui. From what I comprehend, Webpack auto ...

Node.js/Firebase function to delete an item from a JSON object and update the existing items

I'm currently facing a challenge with updating a JSON file in Firebase after deleting an item using the .delete() function. Here is the original JSON data before deletion: "data": [ { "position": "3", ...

Extracting a data element from a JSON array nested within an object

I am attempting to retrieve a value from a JSONP web-service, however I am unsure of the method to access this specific value within the JSON array. $('#bookThumbnaill').attr('src', bookDetails.volumeInfo.imageLinks.thumbnail); $(&apo ...

Issue with Swiper JS carousel overflowing in Bootstrap 4 column

I've been attempting to embed a Swiper JS carousel within a Bootstrap 4 col class div, but the carousel refuses to stay inside the designated col container. Here's a visual representation of what I'm aiming for: https://i.sstatic.net/lgicC. ...