0

I have a table and on each row I add some attributes that later I need to get when I click on the row with jQuery.

Here is a sample of a <tr> element:

<tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">
   <td class="sorting_1" tabindex="0">ID 01</td>
   <td>This is a custom descriptiion</td>                                                   
</tr>

I would like to build a json object based on data.* attributes but also adding the column values.

So in this example I would like to get something like this:

{'employeeid':'4', 'access':'none', 'area':'HR', 'data1':'ID 01', 'data2':'This is a custom description'}

Any clue?

4
  • That's completely invalid, it should be data-access etc. Commented Nov 18, 2016 at 3:17
  • @adeneo what do you mean? appreciate your feedback Commented Nov 18, 2016 at 3:18
  • You shouldn't have attributes with periods in them, and you should be using data-attributes, as in a hyphen Commented Nov 18, 2016 at 3:18
  • Great feedback let me change that in my code and in the question here...:) Commented Nov 18, 2016 at 3:19

1 Answer 1

1

If you use valid data attributes

<tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">

All you need is $(element).data() to get all of them as an object.
If you wanted to add the text from all the children elements as well, you could extend that object

var tr   = $('tr[data-id="1"]');
var data = tr.data();

$.extend(data, $('td',tr).toArray().reduce(function(a,b,i) {
	a['data' + (i+1)] = $(b).text();
    return a;
}, {}));

console.log(data)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
    <tr data-id="1" data-employeeid="4" data-acceess="none" data-area="HR">
        <td class="sorting_1" tabindex="0">ID 01</td>
        <td>This is a custom descriptiion</td>
    </tr>
</table>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.