Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Jquery get value of previos element not work

Hi i try to get value of table col with jquery
try using prev() function but this stil not work

<table>
      <tr>
        <td>phone:</td>
        <td class="phone">0525671341</td>
      </tr>
      <tr>
        <td>phone 2:</td>
        <td class="phone2">053211341</td>
      </tr>
      <tr>
        <td>email:</td>
        <td class="email">test@gmail.com</td>
      </tr>
    </table>
    <hr>
    <button class="btn btn-primary btn-sm editUser" >edit <i class="fa-regular fa-pen-to-square"></i></button>

$(document).ready(function(){
   $('.editUser').on('click',function() {
   var email=$(this).prev(".email").text();
   alert (email);
   });
});

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The deal is that the <td class="email"> is not the previous element.

The simple fix is to change:

var email=$(this).prev(".email").text();

to:

(update)
Since you mentioned having multiple tables. Assuming there is the same table/hr/button element order, then this should work:

var email=$(this).prev().prev().find('.email').text();
// the first prev() is the <hr> tag.
// the second prev() is the <table> tag.
// then find the element with the email class and get the text()

Try the runnable example below:

$(document).ready(function(){
   $('.editUser').on('click',function() {
   var email=$(this).prev().prev().find('.email').text();
   alert (email);
   });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
      <tr>
        <td>phone:</td>
        <td class="phone">0525671341</td>
      </tr>
      <tr>
        <td>phone 2:</td>
        <td class="phone2">053211341</td>
      </tr>
      <tr>
        <td>email:</td>
        <td class="email">test@gmail.com</td>
      </tr>
    </table>
    <hr>
    <button class="btn btn-primary btn-sm editUser" >edit <i class="fa-regular fa-pen-to-square"></i></button>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading