Shariati
Shariati

Reputation: 119

Get selected option value from specific select

I can not get the selected <option> value. <select>s are formed dynamically from database into table rows. All <select>s have same class name.

Here is my HTML:

<tr>
    <td class="std_code">2014-1-10</td>
    <td>Student 10</td>
    <td>66</td>
    <td>100</td>
    <td>66</td>
    <td>
        <select class="degree_accept_id">
            <option value="1">BA(LAW)</option>
            <option value="2">BE(EE)</option>
        </select>
    </td>
    <td>17 November 2014</td>
    <td>
        <a href="" class="ee_accept_suggestion"><i class="fa fa-check fa-lg"></i></a>
    </td>  
</tr>
<tr>
    <td class="std_code">2014-1-9</td>
    <td>Student 9</td>
    <td>69</td>
    <td>100</td>
    <td>69</td>
    <td>
        <select class="degree_accept_id">
            <option value="1">BA(LAW)</option>
            <option value="2">BE(EE)</option>
        </select>
    </td>
    <td>17 November 2014</td>
    <td>
        <a href="" class="ee_accept_suggestion"><i class="fa fa-check fa-lg"></i></a>
    </td>  
</tr>
<tr>
    <td class="std_code">2014-1-8</td>
    <td>Student 8</td>
    <td>71</td>
    <td>100</td>
    <td>71</td>
    <td>
        <select class="degree_accept_id">
            <option value="1">BA(LAW)</option>
            <option value="2">BE(EE)</option>
            <option value="3">BE(ME)</option>
        </select>
    </td>
    <td>17 November 2014</td>
    <td>
        <a href="" class="ee_accept_suggestion"><i class="fa fa-check fa-lg"></i></a>
    </td>  
</tr>

JS code:

<script>
    $(document).ready(function() {
        $('.ee_accept_suggestion').click(function(e) {
            e.preventDefault();
            var std_code = $(this).parent().siblings(".std_code").text();
            //var selected_degree = $(".degree_accept_id option:selected", this).attr("value");
            //var selected_degree = $(this).val();
            var selected_degree = $("select.degree_accept_id").val();
            alert(selected_degree);
        });
    });
</script>

The problem: alert always shows 1.

Upvotes: 1

Views: 1925

Answers (1)

Travis J
Travis J

Reputation: 82337

If you want the selected value of the dropdown relative to the click event, use this

$('.ee_accept_suggestion').click(function(e){
 var dropdownValue = $(this).closest('tr').find('.degree_accept_id').val();

What is happening is

  • First, the clicked element is used $(this) and is wrapped in a jQuery object to have access to the API,
  • .closest('tr') searches itself first, and then for the first occurrence of parent nodes which are <tr>.
  • Once the <tr> element is found, .find('.degree_accept_id') will locate the element under that tr classed as "degree_accept_id".
  • jQuery's .val() gets the value associated with an input, select (in this case), or textarea element.

Upvotes: 3

Related Questions