Search code examples
javascriptjqueryjquery-selectors

.next(".myClass") Not Working Jquery


I don't know how to access the value that I want I've tried a lot of things but I don't know how to find my value. Here is my HTML:

<table class="liste">
    <tbody>
        <tr>
            <th>Actions</th>
            <th>Nom</th>
            <th>Coordonnées</th>
            <th>Diplômes</th>
            <th>Profil associé</th>
        </tr>
        <tr>
            <td class="groupe" colspan="5">2014-2015            
                <button class="copyMails" title="Copier les adresses emails">
                     <img src="/images/picto/action_dupliquer.png" alt="">
                    Copier les adresses emails
                </button>
            </td>
        </tr>
        <tr>
            <td>
                <input type="text" class="lstMails" value="myText">
            </td>
        </tr>
        <tr>
            <th>Actions</th>
            <th>Nom</th>
            <th>Coordonnées</th>
            <th>Diplômes</th>
            <th>Profil associé</th>
        </tr>
        <tr>
            <td class="groupe" colspan="5">2014-2015            
                <button class="copyMails" title="Copier les adresses emails">
                     <img src="/images/picto/action_dupliquer.png" alt="">
                    Copier les adresses emails
                </button>
            </td>
        </tr>
        <tr>
            BLABLABLA
        </tr>
        <tr>
            BLABLABLA
        </tr>
        <tr>
            <td>
                <input type="text" class="lstMails" value="myText2">
            </td>
        </tr>
    </tbody>
</table>

Here is my JS:

$("body").on('click', ".copyMails", function() {
    console.log($(this).parent().parent().parent().next('.lstMails').val());
});

I've tried with and with parent with more and less etc. But I don't know how to do this. I want to access the next .lstMails when I click on the button .copyMails


Solution

  • You should use closest() to navigate parent tr then use next() to point to next tr then you can use find()

    Use

    $("body").on('click', ".copyMails",function(){
        console.log($(this).closest('tr').next('tr').find('.lstMails').val());
    });
    

    Update

    $("body").on('click', ".copyMails", function() {
        alert($(this).closest('tr').nextAll('tr:has(.lstMails)').find('.lstMails').val());
    });