Retrieving the current value of the selected option using JQuery

I am working on a feature where I have different quantities in selects after each button click.

  <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button>
                    <select  id="quantity1"  class="ml-1">

                        <option value="4">4</option>

                    </select>

                     <button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button2</button>
                    <select  id="quantity1"  class="quantity ml-1"> 

                        <option value="3">3</option>

                    </select>

In this setup, when I click Button1, I want to receive the quantity 4 and when I click on Button2, I want to receive the quantity 3.

I believe I can achieve this with the following code:

 var nextoption =   $('button[id*="addtocart"]').click(function()  { console.log($(this).closest('select').text()); });

Any help or suggestions would be greatly appreciated. Thank you!

Answer №1

closest() is a useful function for finding the closest parent element that matches the specified selector. However, in this case, since the select elements are siblings, you should use the next() method instead. Additionally, to retrieve the value of the selected option, you can utilize the val() method:

var nextoption = $('button[id*="addtocart"]').click(function() {
  console.log($(this).next('select').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-primary" id="addtocart2">Button1</button>
<select id="quantity1" class="ml-1">
  <option value="4">4</option>
</select>

<button type="button" class="btn btn-sm btn-primary" id="addtocart2">Button2</button>
<select id="quantity1" class="quantity ml-1">
  <option value="3">3</option>
</select>

Answer №2

Utilize the .next() function to access the next sibling element of the buttons and make use of the .val() method to retrieve the current value of a form field.

$("button[id*='addtocart']").on("click", function(){
  console.log($(this).next().val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button1</button>
<select  id="quantity1"  class="ml-1">
   <option value="4">4</option>
</select>

<button type="button" class="btn btn-sm btn-primary" id="addtocart2" >Button2</button>
<select  id="quantity1"  class="quantity ml-1"> 
  <option value="3">3</option>
</select>

Answer №3

You can utilize the :selected selector to target the currently selected option.


$('#addtocart1').click(() => {
  console.log($('#quantity1 option:selected').val());
});

$('#addtocart2').click(() => {
  console.log($('#quantity2 option:selected').val());
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-sm btn-primary" id="addtocart1">Button1</button>
<select id="quantity1" class="ml-1">
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
</select>

<button type="button" class="btn btn-sm btn-primary" id="addtocart2">Button2</button>
<select id="quantity2" class="quantity ml-1">
  <option value="4">4</option>
  <option value="3">3</option>
  <option value="2">2</option>
</select>

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 transitioning a Node.js application from JavaScript to TypeScript incrementally

I have a JavaScript node application that has grown quite large and I am considering migrating to TypeScript for faster development and easier code maintenance. I have installed TypeScript along with the node and mocha types using the following commands: ...

What steps do I need to take to extract the date and month from a single datepicker using the code below?

<div class="col-md-3 pull-left" style="padding:9px"> <input type="text" id="datepicker" class="form-control"> </div> The HTML and C ...

"Disabling Dropzone.js functionality once a file has been selected - here's how

When using my dropzone, I typically choose a file to save first and then click the save button. However, I am facing an issue: how can I disable the dropzone area after selecting a file? I attempted the following approach: accept: function (file, done) { ...

Determine the specific cell involved in an HTML5 drag-and-drop interaction within a table

I've been experimenting with the HTML5 drag and drop functionality in an Angular project. Here's the setup I'm working with: A container containing draggable 'objects' A table where users can drop the dragged elements Following ...

Javascript error - SyntaxError: unexpected token '}' after property list is missing

In my code snippet below: var UserCharacter = { UserID: util.getCookie('u_u'); userUsingThisCharacter: function() { var data = {}; data.UserID = UserCharacter.UserID; $.ajax({ type: "GET", url: util.API_URL + "charact ...

After a push to the router, scrolling is disabled

While working on a Vuejs project, I encountered an issue when trying to change the page of my PWA using this.$router.push();. It seems to work fine everywhere else except when doing it from a modal within a component. The pushed page loads but scrolling is ...

Generating a dataframe with cells that have a combination of regular and italicized text using the sjPlot package functions

I've been trying to set up a basic data table where the genus name in the "Coral_taxon" column is italicized, but the "spp." part following it remains lowercase. I thought of using the expression() function for each row in "Coral_taxon," but so far, I ...

Having trouble with Google Maps Places API autocomplete feature; it's not functioning properly

My goal is to integrate the Google Maps Places API with a search box. To test jQuery autocomplete, I managed to make it work using this simple example: function bindAutocomplete() { var locationSearch = $("input#Location"); locationSearch.autocom ...

How to Create Smooth Transitions for Text Arrays using jQuery's Fade In and Fade Out Features

I need to loop through an array of text and apply jQuery's fadeIn and fadeOut functions to each element. var greetings = ["hi, I'm", "bonjour, je m'appelle", "hallo, ich heiße"] The HTML structure I want is as follows: <h2><span ...

Changes in query parameters on NextJS navigation within the same page do not activate hooks

When utilizing NextJS without SSR, I encountered an issue with basic navigation using different query parameters. Upon the initial arrival on the page/component, everything seems fine as the component gets mounted and URL params change accordingly. However ...

jQuery's Multi-Category Filter feature allows users to filter content

I have been working on creating a filter function for my product list. The idea is that when one or more attributes are selected, it should fade out the elements that do not match. And then, if a filter is removed, those faded-out items should fade back in ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

How can I implement a AJAX GET request with a parameter in ASP.Net Core 2 Razor

Is there a way to send an AJAX GET request in my ASP.Net Core 2 Razor Application with a parameter that needs to be passed to the destination function? For instance, I have a Select field in my HTML. Depending on what value is selected, I want to retrieve ...

struggling to remove the jquery DataTable

I am trying to implement a functionality where a Button, when clicked, clears a data table and reloads it with fresh data. However, I am facing an issue where the data table is not getting cleared upon clicking the button. Below is the code snippet that I ...

Seeking a solution for resizing the Facebook plugin comments (fb-comments) using Angular when the window is resized

Is it possible to dynamically resize a Facebook plugin comment based on the window or browser size? I want the fb-comment div to automatically adjust its size to match the parent element when the browser window is resized. <div id="socialDiv" class="c ...

Exploring Angular modules has shed light on a certain behavior that has left me puzzled - specifically, when diving into JavaScript code that includes the

I am currently working with angularjs version 1.4.3 and I find myself puzzled by a certain segment of code in the Jasmine Spec Runner that has been generated. Upon generation, Jasmine (using ChutzPath) creates this particular piece of code: (function ...

jQuery: Automatically scroll to the end of the div based on the height of the content within

I have successfully developed a chat feature that is functioning perfectly. However, I am encountering an issue with making my div scroll to the bottom. The height of the div is calculated as calc(100% - 60px);. This particular div retrieves messages from ...

What is the most effective approach to building this function in React JS rather than the existing .map method?

Hello, I'm fairly new to all of this so please bear with me. I've been working on developing a search function for my app, but I've encountered a problem. The search function in my header component is being rendered like this in my index: &l ...

Ways to determine the success of $wpdb->query and retrieve the outcome

Currently, I am in the process of developing a WordPress website, I have implemented a form that allows users to make modifications and update the database: Below is the HTML/PHP code snippet: echo '<form class="form-verifdoc" target=&q ...