views:

27

answers:

2

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' />
+2  A: 

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

$(".addToButton").live('click', function (e) {
  var sel = $(this).prevAll(".addToList:first"),
      val = sel.val(),
      text = sel.find(':selected').text();    
});
Nick Craver
Caching, Nick, caching!
Andy E
@Nick Craver - i want to leverage the class name as what if i stick something after the dropdown and before the button in the future. is there a more future-proof solution
ooo
@ooo - updated with a slightly more future-proof way to do this, searching all previous siblings until `.addToList` is found
Nick Craver
@Nick Craver - at those supposed to be commas or semicolons at the end of the first and second lines ??
ooo
@ooo - commas, using a single `var`, you could do semicolons, and a `var` on each line as well.
Nick Craver
@Nick Craver - ah .. thanks, didn't realize this (i apologize for by being naive and questioning your correctness :) )
ooo
@ooo - there are no stupid questions!, well there *are*, but that wasn't one :)
Nick Craver
A: 

You can do this with the following code:

$(".addToButton").live('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.

lonesomeday