Ashish Bahl
Ashish Bahl

Reputation: 1493

Get the row id that has selected option from dropdown - jQuery

What I am trying to do in my project is that I have a table with two rows.

First row has 3 columns and in each td, there is a dropdown.

Second row has only 1 column.

Now, I have to fetch the id of the td which has a particular selected value from the dropdown.

What I am trying to do is this :

$("#R1C1,#R1C2,#R1C3,#R2C1").append($("#selectServices"));
     $(" #selectServices").on('change', function (){
        if($("#selectServices option:selected" ).text()=="Check In"){
            // need code to get td id from select dropdown with text as Check In
        }
     });
});

Where R1C1 stands for row 1 column 1 and so on..
selectServices is the id for my dropdown
Check In is the required option value I want from my dropdown

Upvotes: 2

Views: 3706

Answers (2)

Nikhil Maheshwari
Nikhil Maheshwari

Reputation: 2248

I think, this is what you are looking for. Check the desired value on change of dropdown itself.

HTML :

<table id="table-id">
  <tr>
    <td id="#R1C1">
      <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </td>
    <td id="#R1C2">
      <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </td>
    <td id="#R1C3">
      <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </td>
  </tr>
  <tr>
    <td id="#R2C1">
      <select>
        <option value="volvo">Volvo</option>
        <option value="saab">Saab</option>
        <option value="mercedes">Mercedes</option>
        <option value="audi">Audi</option>
      </select>
    </td>
  </tr>
</table>

JavaScript :

$(document).ready(function() {
  $("select").on('change', function() {
      if($(this).val() == "mercedes") {
        console.log($(this).parent()[0].id)
      }
  });
});

JSFiddle : https://jsfiddle.net/nikdtu/yk0qzd85/

Upvotes: 3

Zakaria Acharki
Zakaria Acharki

Reputation: 67505

You could use closest() to go up to the parent td then use attr() to get the id attribute, like :

$("#selectServices option:selected").closest('td').attr('id');

Hope this helps.

Upvotes: 3

Related Questions