Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get previous selected dropdown item

i have the following code where i have a dropdown list (with class="addToList" and followed by a button (Class="addtoButton"):

When i click on the button, i want to grab the current selected value and text from the previous dropdown list.

$(".addToPortalButton").live('click', function (e) {

// grab the previous dropdown list value and text here.

});

what is the easiest way to doing this using jquery.

Here is the html:

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />

<select class="addToList" id="Teams" name="Teams">
     <option></option>
    <option value="49">Team 1</option>
    <option value="22">Team 2</option>
</select>
<input type='button' class="addToButton" value='Add to' />
like image 805
leora Avatar asked Oct 28 '10 10:10

leora


People also ask

How do you get previous selected value in dropdown in react?

To fetch the selected value from the select element, you can use the onChange event handler prop. Just like the input or textarea elements, you can use the onChange event handler to get the value from the event object.

How do I get the selected value select drop-down?

Method 1: Using the value property: The value of the selected element can be found by using the value property on the selected element that defines the list. This property returns a string representing the value attribute of the <option> element in the list. If no option is selected then nothing will be returned.

How to get selected value from dropdown in HTML?

The value property sets or returns the value of the selected option in a drop-down list.


2 Answers

You can use .prev() or .prevAll() to get the <select> before like this:

Edit: for newer versions of jQuery where .live() has been deprecated, the new .on() syntax is:

$(document).on('click', '.addToButton', function (e) {
  var sel = $(this).prevAll('.addToList:first'),
      val = sel.val(),
      text = sel.find(':selected').text();    
});

Older version:

$(".addToButton").live('click', function (e) {
  var sel = $(this).prevAll(".addToList:first"),
      val = sel.val(),
      text = sel.find(':selected').text();    
});
like image 53
Nick Craver Avatar answered Oct 28 '22 12:10

Nick Craver


You can do this with the following code:

$(".addToButton").on('click', function (e) {

    var $el = $(this).prev().find('option:selected');

});

You can then use $el.val() and $el.text() to get the value and text respectively.

like image 45
lonesomeday Avatar answered Oct 28 '22 11:10

lonesomeday