FAISAL
FAISAL

Reputation: 459

Store data from table into associative array

I am trying to store data into an associative array from table. Here is my html table code:

<table class="table" border="1" id="eidtPersonalInfoTbl">         
    <tr>    
        <td class="span3 hidden-phone">Name</td>    
        <td class="span5"> Name of Doctor </td>
    </tr>    
    <tr> 
        <td class="span3 hidden-phone">Address</td>
        <td class="span5"> Address of doctor </td>
    </tr>
    <tr>
        <td class="span3 hidden-phone">Area</td>
        <td class="span5"> Area</td>
    <tr>
 <table>

and I am trying to access table values by this code:

<script type="text/javascript">
    $(document).on('click', '.editPersonalInfo', function() {
        modal();
        alert(obj['Name']);
        alert(obj['Address']);
        alert(obj['Area']);
    });

    function modal() {
        var table = $("#eidtPersonalInfoTbl");
        var trs = table.find('tr');
        var obj = {};
        $(trs).each(function(index, row) {
            var field = $(row).find('td').eq(0).text();
            var value = $(row).find('td').eq(1).text();
            obj[field] = [value];
        });
    }
</script>

but it is not working. How I can solve this problem?

Upvotes: 1

Views: 1465

Answers (1)

codingrose
codingrose

Reputation: 15699

You dont have any editPersonalInfo class in HTML markup. Use #eidtPersonalInfoTbl instead.

Try:

$(document).on('click', '#eidtPersonalInfoTbl', function () {
    var obj = modal(); //store object in a variable
    alert(obj['Name']);
    alert(obj['Address']);
    alert(obj['Area']);
});

function modal() {
    var table = $("#eidtPersonalInfoTbl");
    var trs = table.find('tr');
    var obj = {};
    $(trs).each(function (index, row) {
        var field = $(row).find('td').eq(0).text();
        var value = $(row).find('td').eq(1).text();
        obj[field] = [value];
    });
    return obj; //return object
}

Fiddle here.

Upvotes: 2

Related Questions