0

I have the following table

<table id="table_device">
    <tr>
        <td> First td </td>
        <td> Second td </td>
        <td> 
            <select class="base_MD">
                <option>A value</option>
                <option>Another value</option>
                <option>And another one</option>
                ...
            </select> 
        </td>
        <td> The value </td>
    </tr>
    <tr></tr>
    <tr></tr>
    ...
</table>

How do I set the <select> where the <option> matches with the 4th child (named 'The value') for each <tr> tag?

EDIT

I tried the following

        $('#table_device').find('tr').each(function()
        {
            var value = $(this).find(':nth-child(4)').html();

            $('select').each(function()
            {
                if($(this).text() == value)
                {
                    var id = $(this).val();
                }

                $(this).eq(id).prop('selected', true);
            })
        });

But it did not work ... I'm sure it's not that complicated but my head will explode soon

1
  • 2
    What have you tried? What parts of the API have you looked at? Commented Jul 27, 2015 at 14:20

2 Answers 2

1

You can iterate over each select element. get the text from next td and use it to set option by text. Like this:

$('#table_device select').each(function(){
 var nexttdtext = $(this).parent().next('td').text();
  $(this).find("option").filter(function() {
     return this.text == nexttdtext; 
  }).attr('selected', true);​
}); 

Working Demo

Sign up to request clarification or add additional context in comments.

2 Comments

I have another select tag on each tr. Do I have to set a class or ID to the select that I want to setup ?
not required. check the demo. it exactly does what you want
1

Bind an onchange event to the list. Find the selected option and the text inside it. And put it in the first row, last cell...

$(function() {
  $('.base_MD').on('change', function() {
    var value = $(this).find(':selected').text();
    $('#table_device tr:first-child td:last-child').text( value );
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="table_device">
    <tr>
        <td> First td </td>
        <td> Second td </td>
        <td> 
            <select class="base_MD">
                <option>A value</option>
                <option>Another value</option>
                <option>And another one</option>
                ...
            </select> 
        </td>
        <td> The value </td>
    </tr>
    <tr></tr>
    <tr></tr>
    ...
</table>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.