0

In my MVC project, Need to find selected row(tr), first child(td) data-attribute and control tagName also need to set the attribute attr('checked', 'checked');

HTML

<table class="availableProduct">
    <tr>
        <td>
                <input type="checkbox" class="product-group" data-productid="SAP003" 
                data-id="Annual-46-4" data-optionid="46">
        </td>
        <!-- FIND THIS -->
        <td>foobar</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" class="product-group" data-productid="SAP0031" 
            data-id="Annual-46-14" data-optionid="461">
        </td>
        <!-- FIND THIS -->
        <td>foobar2</td>
    </tr>
    <tr>
        <td>
            <input type="checkbox" class="product-group" data-productid="SAP0032" 
            data-id="Annual-46-42" data-optionid="462">
        </td>
        <!-- FIND THIS -->
        <td>foobar2</td>
    </tr>
</table>

jQuery

    $('table.availableProduct tr').click(function (e) {
       var temp=$(this).find("td:eq(0)").html();
    });

jQuery temp variable value is following

<input type="checkbox" class="product-group" 
data-productid="SAP003" data-id="Annual-46-4" data-optionid="46">

On this selection want to do the following

  • read all data-attribute values
  • set attr('checked', 'checked');
  • Need to read the tagName
Tetsuya Yamamoto
  • 24,297
  • 8
  • 39
  • 61
shamim
  • 6,640
  • 20
  • 85
  • 151
  • 1
    Get all attributes: https://stackoverflow.com/questions/4187032/get-list-of-data-attributes-using-javascript-jquery set checked: https://stackoverflow.com/questions/5874652/prop-vs-attr – Pete Jan 21 '19 at 14:09
  • 1
    Get tagname https://stackoverflow.com/questions/5347357/jquery-get-selected-element-tag-name – Pete Jan 21 '19 at 14:19
  • 1
    All easily findable if you actually bothered to do a bit of searching / researching – Pete Jan 21 '19 at 14:20

1 Answers1

1

this refers to the current element clicked

$(this).find('td .product-group'); find the element with class product-group.

Use .data() to get all the data attributes on the element.

Set checked using .prop().

$('table.availableProduct tr').click(function(e) {
  var inp = $(this).find('td .product-group');
  inp.prop('checked', !inp.prop('checked')); // toggle check and uncheck
  var dataAttributes = inp.data();
  console.log(dataAttributes);
});

Demo

Tushar Gupta - curioustushar
  • 58,085
  • 24
  • 103
  • 107