How to use jQuery to retrieve the value of a select box based on the text it

Below is an example of a select box:

        <select id="year">
        <option value="1">1 Year</option>
        <option value="2">2 Years</option>
        <option value="3">3 Years</option>
        <option value="4">4 Years</option>
        <option value="5">5 Years</option>
        <option value="6">6 Years</option>
        <option value="7">7 Years</option>
        <option value="8">8 Years</option>
        <option value="9">9 Years</option>
        <option value="10">10 Years</option>
        </select>

I am looking for assistance on how to retrieve the value of a specific text using jQuery, such as "value of 4 Years". Can someone guide me on this?

Answer №1

To find the value of '4 Years' using the filter method with an exact match, you can use the following code:

$('select option').filter(function(){
    return $(this).text() === '4 Years';
}).val();

If you prefer to use the :contains selector instead, you can achieve the same result with this code:

$('select option:contains(4 Years)').val();

Answer №2

You should consider applying .text() method to the chosen option. For instance:

$('select option:selected').text();

Answer №3

To retrieve the value of the option that has been selected:

$('#year').val();

If you need to select a specific option based on its text:

$("#year option:contains('4 Years')").val();

Best regards.

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

issues with jquery functionality on user control page

For searching through dropdown lists in my project, I have implemented the Chosen jQuery plugin. In the Master page before the closing body tag, ensure to include the necessary CSS and jQuery script files. <link href="/assets/css/chosen.css" rel=" ...

Ensure that a component does not receive a value if the string is equal to an empty string

When passing values to my component, I encountered an issue where some values were empty (""). This resulted in a visual container appearing empty on my view. To resolve this, I need the value not to pass at all if it equals "". <AddIntel initialValues ...

Dealing with problems when uploading images using Django and Jquery ajax

I am encountering some difficulties when attempting to upload an image using Jquery Ajax on my Django 1.7 server. The behavior I experience on my development machine differs from that on my staging machine, making it challenging to pinpoint the exact issu ...

Troubleshooting the Speed of Ionic Scrolling

One of the features in my application involves displaying feeds or a timeline. Below is the ng-repeat code I am using: <div ng-repeat="x in feeds" class="fd-feed-card"> <div class="fd-feed-usr-img"> <img ng-src="{{x.user.media[0 ...

Error in Email Attachment - Invalid Attachment File Path

My workflow is as follows: User selects a local file while filling out an HTML form AJAX sends the form data to my ASMX Public classes use JSON data to create an email (with the file being an attachment) While there are many ...

Encountering an issue with react-native-gesture-handler functionality

When I attempt to utilize react-native-gesture handler, I encounter the following error: : While attempting to find module 'react-native-gesture-handler' from file '/Users/user/Project/index.js', the package '/Users/user/Project/n ...

Take a custom action once all elements have been rendered with ng-repeat

Looking to manipulate a DIV element generated by ng-repeat: <div ng-repeat="data in info" > <div id='plot_{{data.id}}'></div> </div> Here is the sequence of events: Information added to $scope.info ng-repeat exec ...

Steps for displaying the search results in a pop-up box

I'm having trouble figuring out what to put in the '()' of my JavaScript popup function. Can anyone help me with this issue? Thank you! :) <script> // Example of JavaScript popup window function function customPopup(url) { popupWindow ...

Tips for implementing paths instead of GET variables in PHP?

I've encountered an issue where my previous question was closed for the wrong reason. Basically, I have folders that contain a PHP file {dynamic}/blog/index.php. How can I enable someone to access example.com/folders/{dynamic}/blog/unique as if it w ...

What is the best way to vertically center my footer text?

footer { text-align: center; color: #FFF; position: fixed; bottom: 0px; width: 100%; height: 90px; background-color: #464646; } <footer> &copy; Name </footer> I am looking to center my name within the footer, however, it cu ...

The FullCalendar plugin on the list was experiencing functionality issues

I came across this code snippet that is causing me some trouble: .... import { FullCalendarComponent } from '@fullcalendar/angular'; import { EventInput } from '@fullcalendar/core'; import dayGridPlugin from '@fullcalendar/daygrid& ...

Using AngularJS controllers: How can one trigger a controller from within a different controller?

Within my script, I have a list controller defined as follows: define([ 'jquery', 'app' ], function ($,app) { app.controller("ListContacts", function($scope,$route,$http){ $http({ method: 'GET&apo ...

Encountering an "undefined" error when implementing the useReducer hook in React

I'm encountering an error when using the UseReducer hook in React. Even though I have destructured the state object, I still receive this error: const [{previousOperand,currentOperand,operation},dispatch] = useReducer(reducer,{}); return ( ...

Tips for inserting text onto an image using a hover effect

I have designed a section on my website where an image darkens upon hovering, and I would like text to appear centered both horizontally and vertically when the image is hovered over. However, despite my efforts, the text does not display on the image as i ...

New to the game: validating JavaScript forms on the go

I recently developed a form that requires JavaScript validation. Despite referencing a post about inline JavaScript form validation on Stack Overflow, I struggled to replicate the desired outcomes. To aid in troubleshooting, I have set up a JSBin link tha ...

Adding content to the parent element immediately after it is generated using jQuery

Is there a way to trigger $(e).append() as soon as the element e is created without using setTimeout()? I find that method inefficient. Are there any DOM events that can detect changes in a subtree of a DOM element? Usually, I would just add the code to t ...

Ajax - The Infamous "Access-Control-Allow-Origin" Issue

I'm currently working with the Livestream API in an attempt to check if a specific channel is live, but I keep encountering this error message: XMLHttpRequest cannot load http://channel.api.livestream.com/1.0/livestatus?channel=huskystarcraft. Origin ...

Optimal methods for handling server exception messages during an AJAX request

My question boils down to this: When I send a $.ajax request to my server for server-side validation, how should I handle the validation response? I see two main options: // Server handled error: $.ajax({ url: 'controller/action', data: { ...

Storing only the initial letter of the text area in the database

First and foremost, I want to express my gratitude to all of you who have provided me with invaluable advice throughout the past few months. This project has been a tremendous learning experience for me, but I've hit a roadblock when it comes to using ...

I am able to craft a function that takes in an integer and produces an array filled with pairs of integers [a, b] arranged in ascending order of both a and b

I'm currently stuck on a practice problem in my software engineering bootcamp and could really use some help to steer me in the right direction. The task is to create a function called generatePairs that takes an integer as input and returns an array ...