Home > Software engineering >  Jquery get value of previos element not work
Jquery get value of previos element not work

Time:01-02

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 >0525671341</td>
      </tr>
      <tr>
        <td>phone 2:</td>
        <td >053211341</td>
      </tr>
      <tr>
        <td>email:</td>
        <td >[email protected]</td>
      </tr>
    </table>
    <hr>
    <button  >edit <i ></i></button>

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

CodePudding user response:

The deal is that the <td > 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 >0525671341</td>
      </tr>
      <tr>
        <td>phone 2:</td>
        <td >053211341</td>
      </tr>
      <tr>
        <td>email:</td>
        <td >[email protected]</td>
      </tr>
    </table>
    <hr>
    <button  >edit <i ></i></button>

  • Related