Steve Steve - 4 months ago 7
jQuery Question

Getting the individual details

form:

<label>First Name:</label><input type="name" class="form-control" id="fname">
<label>Last Name:</label><input type="name" class="form-control" id="lname">
<button class="btn btn-primary" id="add">Add</button>


I am adding the first name and last name into the table if i click on add button.

table:

<table class="table table-bordered" id="table">
<thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td><td>Options</td></tr></thead>
<tbody id="tbody"></tbody>
</table>


jQuery:

$(function(){
var i=0;
$(document).on('click', '#add', function (e)
{
e.preventDefault();
var fname=$('#fname').val();
var lname=$('#lname').val();
if(fname=='' || lname=='')
{
swal('Both fields are required!');
}
else
{
i++;
$('#tbody').append('<tr><td>'+i+'</td><td>'+fname+'</td><td>'+lname+'</td><td><button id="view" class="btn btn-info">Details</button></td></tr>');
$('#showf').append(fname);
$('#showl').append(lname);
}

document.getElementById('fname').value = "";
document.getElementById('lname').value = "";
});
});


Now, I need to show respective first name and last name if I click on details.

$(document).on('click', '#view', function (e) {
swal('I am trying. ...');
});

Answer

You can do it like following. You are duplicating the id #view use class view instead.

$(document).on('click', '.view', function(e) {
    var tr = $(this).closest('tr');
    var firstName = tr.find('td').eq(1).text();
    var lastName = tr.find('td').eq(2).text();
    alert(firstName + ' ' + lastName);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table table-bordered" id="table">
    <thead><tr><td>S.N.</td><td>First Name</td><td>Last Name</td><td>Options</td></tr></thead>
    <tbody id="tbody">
        <tr>
            <td>1</td>
            <td>fname</td>
            <td>lname</td>
            <td><button class="view btn btn-info">Details</button></td>
        </tr>
        <tr>
            <td>2</td>
            <td>fname 2</td>
            <td>lname 2</td>
            <td><button class="view btn btn-info">Details</button></td>
        </tr>
    </tbody>
</table>