What is the best way to choose the final index value in a drop-down menu?

Is there a way to read and select the last index value in a drop-down using JavaScript?

Here is an example of the HTML code:

<select name="unqiue">
  <option value="number:1" label="1">1</option>
  <option value="number:2" label="2" selected="selected">2</option>
  <option value="number:3" label="3">3</option>
  <option value="number:4" label="4">4</option>
</select>

Please note that the values in the drop-down could vary, but I specifically need to programmatically select the last value '4'.

Answer №1

To retrieve the last option in a select element with the name "unique", you can utilize document.querySelectorAll('select[name="unqiue"] option:last-child')[0]:

For instance:

var lastOpt = document.querySelectorAll('select[name="unqiue"] option:last-child')[0];

//
// To choose this particular element:
//

lastOpt.selected = true;

//
// To obtain the value
//

var val = lastOpt.value.replace(/\D*/, '');

console.log(val);
<select name="unqiue">
    <option value="number:1" label="1">1</option>
    <option value="number:2" label="2" selected="selected">2</option>
    <option value="number:3" label="3">3</option>
    <option value="number:4" label="4">4</option>
</select>

Answer №2

Your illustration implies that the `name` attribute is a unique identifier for a `select` element in your HTML code.

To access this element, you can utilize `document.querySelector`, allowing you to retrieve and modify its content.

const unique = document.querySelector('select[name="unqiue"]');
const valueLast = unique.lastElementChild.value;
console.log(valueLast);
const textLast = unique.lastElementChild.textContent;
console.log(textLast);
unique.selectedIndex = unique.length - 1;
<select name="unqiue">
  <option value="number:1" label="1">1</option>
  <option value="number:2" label="2" selected="selected">2</option>
  <option value="number:3" label="3">3</option>
  <option value="number:4" label="4">4</option>
</select>

ParentNode.lastElementChild

Node.textContent

HTMLSelectElement.selectedIndex

HTMLSelectElement

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

Something is wrong with the conditional compilation in the JavaScript code

I encountered a "Conditional compilation is turned off" error in my JavaScript code. How can I resolve this issue? var <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="176264726559767a722a6765727a763976397679747f786557626739786 ...

The duration spent on a website using AJAX technology

We conducted an online survey and need to accurately calculate the time spent by participants. After using JavaScript and PHP, we found that the calculated time is not completely accurate. The original script was sending server requests every 5 seconds to ...

The search functionality in an Html table is currently malfunctioning

Currently, I am working on developing a search mechanism in HTML. It seems to be functioning properly when searching for data for the first time. However, subsequent searches do not yield the expected results. Additionally, when trying to search with empty ...

Adding rows to a Datatable using an object array in rows.add()

Attempting to refresh my current Datatable by fetching new data using an Ajax function. Despite trying various solutions from other sources, the table does not update as expected. The function being used is shown below: $.ajax({ url: "<?php echo s ...

I am experiencing difficulties in accessing the DOM

I have implemented jQuery $.ajax to dynamically load data into table rows as shown below: <table id='row-data'> <tr><td>1001</td></tr> <tr><td>1322</td></tr> <tr><td>15 ...

Executing tasks in a While loop with NodeJS and attaching actions to a Promise

I am relatively new to incorporating Promises in NodeJS. My current task involves creating a promise dynamically with multiple actions based on the characters found in a string. //let actions = []; getPromise = get(srcBucket, srcKey); // Retrieve the imag ...

Navigating through external JSON data in a Node.js and Express application, and rendering the data using Jade

After going through various examples and solutions in related questions on StackExchange in an attempt to solve my issue, I have decided to post my question. My ultimate goal is to access complex JSON data via an API and REST. I intend to import this data ...

How can AngularJS effectively parse JSON data containing HTML elements?

We are experiencing difficulties in reading a json file containing html content. Here is the code snippet with the json data we are working with: Json data: { "aboutContent": { "listItems": [{ "title": "Investors", "de ...

Is it optimal to count negative indexes in JavaScript arrays towards the total array length?

When working in JavaScript, I typically define an array like this: var arr = [1,2,3]; It's also possible to do something like: arr[-1] = 4; However, if I were to then set arr to undefined using: arr = undefined; I lose reference to the value at ...

What is the best way to retrieve the canonicalized minimum and maximum values within the beforeShow method of jQuery UI's datepicker?

I have a pair of datepicker elements that I want to function as a range. When a value is set in the "low" datepicker, it should adjust the minDate and yearRange in the other datepicker, and vice versa with the "high" datepicker. The challenge I'm faci ...

Storing a PDF created with Laravel in a queue

I have a tool that converts HTML to PDF and saves it locally. I also use a live URL to fetch another PDF and save it on my local machine. Then, I utilize a Laravel library to merge both PDFs into a single file through embedding. Previously, this process ...

Make sure to use dispatch when updating the array to prevent any potential infinite loops

I am currently working with JSX to create a function that reads user profiles and updates them upon clicking a button. The object userProfiles contains existing user profile data, which should be updated by combining the current contents with those from ne ...

Utilizing multiple div IDs within the same script functionality

I have multiple dropdown menus on a webpage, and whenever an onchange event happens with any of these menus, I want to utilize the same block of code rather than creating individual scripts for each menu's id. This approach is preferred as the page ma ...

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

Crashes within an HTML5 Canvas

Having recently started to explore Javascript and working with canvas elements, I've encountered a roadblock when trying to implement collision detection for the canvas walls. Typically, I have a small square drawn on the canvas that I can move aroun ...

Every time I attempt to make a "post" request to the SailsJS server, I encounter a 403 CSRF Mismatch error

Having an issue with my sailsJS server. I am attempting to send a post request from a client on a different domain. I am sending _csrf from /csrfToken, but encountering a 403 csrf mismatch repeatedly. The client-side code appears as follows: $.ajax( ...

JavaScript Automation Script for QuickTime Screen Recording

Recently, I've been working on a JavaScript Automation script to record my screen on my Mac. However, I encountered an issue with the API when it reaches the line doc.close(). QuickTime would hang indefinitely and eventually my Script Editor would tim ...

Selecting multiple objects in FabricJS on mouse click

Can anyone provide suggestions on how to select multiple objects on a canvas with a mouse click? I only want to select objects that overlay the point. From my understanding, the target of the mouse event is always the top-most object. I have tried binding ...

The specified subpath './lib/tokenize' does not match any defined "exports"

As a newcomer to React, I've been facing some challenges while trying to get started. Despite searching on Google and other platforms, I couldn't find a solution to my problem. I was attempting to run code from a YouTube channel called Lama Dev b ...

Customizing error messages in Joi validationorHow to show custom

Hi there, currently I am utilizing "@hapi/joi": "^15.1.1". Unfortunately, at this moment I am unable to upgrade to the most recent Joi version. This represents my validation schema const schema = { name: Joi.string() .all ...