Get rows from a table by a value with Jquery

3

I have a table, with a select , in each row, and when I click a button I want to get all the items in the table where select option has value.

<table id="myTable">
<span class="result"></span>
    <thead>
        <tr>
            <th>Nome</th>
            <th>Status</th>
        <tr>
    </thead>
    <tbody>
    <tr>
        <td>xyz</td>
        <td>
            <select>
                <option class="op" value="0">-- Selecione --</option>
                <option class="op" value="1">-- Bloqueado --</option>
                <option class="op" value="2">-- Ativo --</option>
            </select>
        </td>
        </tr><tr>
        <td>abc</td>
        <td>
            <select>
                <option value="0">-- Selecione --</option>
                <option value="1">-- Bloqueado --</option>
                <option value="2">-- Ativo --</option>
            </select>
        </td>
        </tr>
    </tbody>
</table>
<span class="status"></span>
<button class="row" id="btnAdicionar" type="button" >Adicionar</button>    

How can I get to wipe this table and pick up any items that are not 0?     

asked by anonymous 08.04.2016 / 21:35

2 answers

2

Here's a suggestion:

$('#btnAdicionar').on('click', function() {
    // gera coleção jQuery, converte para nativa com ".get()"
    var selectsAtivos = $('select').filter(function() {
        return this.value == '2';
    }).get();

    // usando array nativa
    var tds = selectsAtivos.reduce(function(arr, el) {
        var tr = $(el).closest('tr'); // aqui procura o "tr" pai do select
        return arr.concat(tr.find('td').get()); // aqui vai buscar os "td" que estão dentro do "tr" que encontrámos na linha de cima
    }, []);
    $(tds).css('color', 'red'); // só para o exemplo, aqui mudam de côr os selecionados.
});

jsFiddle: link

    
10.04.2016 / 11:16
2
<table id="myTable">
<span class="result"></span>
    <thead>
        <tr>
            <th>Nome</th>
            <th>Status</th>
        <tr>
    </thead>
    <tbody>
        <td>xyz</td>
        <td>
            <select>
                <option class="op" value="0">-- Selecione --</option>
                <option class="op" value="1">-- Bloqueado --</option>
                <option class="op" value="2">-- Ativo --</option>
            </select>
        </td>
        <td>xyz</td>
        <td>
            <select>
                <option value="0">-- Selecione --</option>
                <option value="1">-- Bloqueado --</option>
                <option value="2">-- Ativo --</option>
            </select>
        </td>
        ...
    </tbody>
</table>
<span class="status"></span>
<button class="row" id="btnAdicionar" type="button" >Adicionar</button>
  

Below we have created a simple line of searching for the field returning value different from 0

08.04.2016 / 22:48