Search code examples
javascriptjquery

alert src of a button on click in jquery


this is my jquery code; but it gives me (undefined).

$(document).ready(function(){
    $('.items > tbody > tr').click(function() {
        var src = $(this).find('a[title="View"]').attr('src');
        alert (src)
    });
});

the HTML code is :

<table class="items">
<tbody>
    <tr>
        <td></td>   
        <td></td>   
        <td></td>   
        <td></td>
        <a title='View' src="main.php"></a> 
        <a title='find' src="index.php"></a>    
    </tr>
</tbody>

Solution

  • The problem is that your anchor tags <a> are out of <tr> family. You have to bring them inside <td> so they become children of <tr>

    $(document).ready(function(){
        $('.items > tbody > tr').click(function() {
            var src = $(this).find('a[title="View"]').attr('src');
            alert (src)
        });
    });
    tr{
      background:#ff8800;
      height:40px;
    }
    table{
      width:100%;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <table class="items">
    <tbody>
        <tr>
            <td></td>   
            <td></td>   
            <td></td>   
            <td></td>
            <td>
              <a title='View' src="main.php"></a> 
              <a title='find' src="index.php"></a>
            <td>
        </tr>
    </tbody>