Is there a way to utilize Javascript to select multiple options and store them in an array?

I'm trying to create an array with selected values in Javascript without using jQuery. I've come across many solutions that involve jQuery, but they don't work with my existing code. Below is the part of my code that's causing trouble:

    var c = new Array();
      var cat_ = _("cat_");
     for(i=0;i<cat_.options.length;i++){
        c.push(cat_.options[i].value);
    }

    alert(c);

The above code successfully loads all options into the array, but I specifically need only the selected items. I want a solution that uses pure JavaScript, no jQuery. Any help would be greatly appreciated.

Answer №1

If you had a <select> element with multiple selected options and needed to obtain an array of the selected option elements or an array of their values, you could achieve this using the following method:

function retrieveSelection() {
  var selected = document.getElementById('sel').selectedOptions;
  var selectedArray = Array.prototype.slice.call(selected);
  alert(selectedArray);
  var selectedValues = selectedArray.map(function(option) { return option.value; });
  alert(selectedValues);
}
<select id="sel" size="6" multiple>
  <option>1</option>
  <option>2</option>
  <option>3</option>
  <option>4</option>
  <option>5</option>
  <option>6</option>
</select>
<button onclick="retrieveSelection()">Retrieve Selection!</button>

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

Tips on using JQuery to extract form field information from a drop-down menu, display it in a div, and then compare it with the subsequently

In my HTML file, I am using two dropdown lists and JQuery for validation. First, I need to save the selected items from both dropdown lists in a variable and then compare them with the next selection. If the data from both dropdown lists match, an alert m ...

Unexpected database query result in Node.js

In my newuser.js file for a node.js environment with a mongodb database managed through mongoose, I have the following code: //newuser.js //This code is responsible for creating new user documents in the database and requires a GET parameter along with a ...

Most Effective Method for Directing Users to Mobile Website

How do you prefer to guide users to a custom mobile site, such as redirecting from mysite.com to m.mysite.com or mysite.com/m? I previously experimented with the Detect Mobile Browsers JS solution, which seemed promising. However, I noticed that it initia ...

Sending a two-dimensional array through an HTML form field using JavaScript

Prior to reading: Please note that if you are only interested in answering the question, you can skip ahead to "The Question" at the end of this post. My current project involves developing a feature for a website that enables users to upload and share pr ...

What is the best way to add a value to the value attribute of a div using JavaScript?

Is there a way to insert a value into the value attribute of a div using Internet Explorer 9? I have attempted various JavaScript functions, but so far I can only modify the content inside the div and not the value attribute itself. <div id="mydiv" val ...

Load the page's content gradually, without needing to wait for all the content to be fully loaded

I am facing an issue with a webpage that displays 10 different items, each of which has a slow loading time. Currently, the entire page waits for all 10 items to fully load before displaying anything. I am interested in finding out if it is feasible to sh ...

Connecting two tables in an express API

Currently, I am in the process of developing an API using Express.js. At this stage, my initial tests are functioning correctly. My goal now is to retrieve values from two separate tables. For example, consider the following 2 tables: Table_A Id: 1, Name: ...

Navigating through and extracting data from an object in JavaScript

Given the function call destroyer([1, 2, 3, 1, 2, 3], 2, 3);, I am trying to retrieve the last 2, 3 part after the initial array. However, I am unsure about how to achieve this. When I use return arr[6]; or return arr[1][0], both statements do not return ...

Can a node.js file be exported with a class that includes IPC hooks?

[Node.js v8.10.0] To keep things simple, let's break down this example into three scripts: parent.js, first.js, and second.js parent.js: 'use strict'; const path = require('path'); const {fork} = require('child_process&apo ...

What is the process for transferring a Python variable to JavaScript when the Python code is a cgi script?

I am currently working on a JavaScript file where I am attempting to assign a variable based on data received from a Python CGI script. My approach involves using the Ajax GET method to retrieve the data and set the variable within that method. Below is a ...

Is it possible to receive live updates from a MySQL database on a webpage using node.js and socket.io?

I've been following a tutorial that teaches how to receive real-time updates from a MySQL database using Node.js and Socket.io. Check it out here: Everything seems to work fine on the webpage. I can see updates in real-time when I open the page on tw ...

Encountering error #426 in NextJs when the app is loaded for the first time in a new browser, but only in a

Encountering a strange error exclusively in production, particularly when loading the site for the first time on a new browser or after clearing all caches. The website is built using nextjs 13.2.3 and hosted on Vercel. Refer to the screenshot below: http ...

Troubles encountered while implementing crypto-js in Parse Cloud Code for an iOS mobile app

For my iOS app, I have implemented Parse as the backend and want to ensure the data transmitted between Parse and the device is encrypted. To achieve this, I have turned to Parse Cloud Code for server-side encryption and decryption of all data exchanges. ...

Caution: It is important that every child within an array or iterator is assigned a distinct "key" property

As a new developer in ReactJS, I have created a table using ReactJS on the FrontEnd, NodeJS on the BackEnd, and MySQL for the database. My goal is to retrieve data with a Select request on the table. For my frontend: class ListeClients extends Component ...

MongoDB (Potential number of _id variations)

In the realm of mongoose, there exists a model named Post (defined as var Post = new Schema({...});). Each time a new instance of the Post model is created (var post = new Post({...}); post.save(function (error) {...});), it is assigned a special item kn ...

Is it a shallow copy or something else when updating state in React JS?

I am currently dealing with a particular state within my application: const [work, setWork] = useState([ { company: "Company", position: "President", website: "example.com", startDate: "2013-01-01", endDate: "2014-01- ...

A guide to effectively converting and parsing a class object that includes Uint8Array elements

After stringifying a class object that contains a property in Uint8Array, and then parsing it later, the property is no longer in Uint8Array format. Here's an example: class Example { title:string; byteData:Uint8Array; ...

Can state be controlled by both the parent and children within the same element?

I am facing a situation where I have a component that requires updating the value from its parent, but also needs to handle user input changes without having to pass them back to the parent. See this scenario in action with this example: https://codesandbo ...

What is the best way to save nested lists in a MYSQL database?

I am trying to figure out the best way to store this list of lists in MySQL, but I'm not sure how to go about it. list[x][y] contains items structured as {li:[{x:x,y:y}] , pos:{x:y}} list[x][y].li[z].x list[x][y].li[z].y list[x][y].pos.x list[x][y]. ...

What kind of data does this collection hold, and what is the best method to retrieve its stored values?

I recently received a code to program a logic for and I have successfully figured out my algorithm. However, I am facing difficulty determining the datatype of a particular declaration. My task involves comparing the values of "skills" in each row to &apos ...