Get the column number from among the "prime" elements

0

I have the following html structure:

<tbody> 

<tr>
    <td><input type='text' class='celda clave' value='1'></td>
    <td>
        <select class='celda'>
            <option selected='true' disabled='disabled'>veracruz</option>
            <option>Veracruz</option>
            <option>Boca del Rio</option>
        </select>
    </td>
    <td><input type='text' class='celda' value='123'></td>
    <td><input type='text' class='celda' value='oscar'></td>
    <td><input type='text' class='celda' value='daniel'></td>
    <td><input type='text' class='celda fecha' value='2017-11-01'></td>
</tr>

</tbody>

The table looks like this:

I am looking for when entering a value in an element with class 'cell', to obtain that number of column has been entered for then to make modifications in the database. So if, for example, a new value is entered in the "Writing" column, I would have to return the number 2 (taking into account that the index starts at 0). If you enter a new value in the "Acquirer" column, you should return the number 4.

Before using tables this was solved with:

$(this).index();

But now, since the INPUT elements are inside the TD elements, this function returns 0.

    
asked by Oscar Díaz 21.11.2017 в 02:37
source

1 answer

1

To achieve what you want, just select the direct parent of the element to which the value has been modified and apply the function index() , like this:

$(".celda").change(function(){
    var indice = $(this).parent().index();
    
    console.log('El índice modificado es el ' + indice)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tbody> 

    <tr>
        <td><input type='text' class='celda clave' value='1'></td>
        <td>
            <select class='celda'>
                <option selected='true' disabled='disabled'>veracruz</option>
                <option>Veracruz</option>
                <option>Boca del Rio</option>
            </select>
        </td>
        <td><input type='text' class='celda' value='123'></td>
        <td><input type='text' class='celda' value='oscar'></td>
        <td><input type='text' class='celda' value='daniel'></td>
        <td><input type='text' class='celda fecha' value='2017-11-01'></td>
    </tr>

    </tbody>
</table>
    
answered by 21.11.2017 / 02:45
source