Search code examples
javascriptjqueryhtmlasp.net-mvccheckbox

How to get data element of checkbox on change event


I've got a dynamic table of items with checkboxes next to each item. When a user selects a checkbox I want to grab the "Name" item from the table and add it to a textbox. See image:

enter image description here

The way I'm trying to accomplish this is by adding a "change" event to every checkbox and populating it's "data-name" element with the name of the text.

<tbody>
            @foreach (var item in Model.Items)
            {
                <tr>
                    <td><input type="checkbox" name="selectBox" data-name="@item.Name" /></td>

As you can see I'm populating data-name with the item name as a way to get around pulling it directly (which I don't know how to do). Now in javascript/jquery I'm tying an event to every checkbox and attempting to get the data element using the following code:

$('input[name=selectBox]').change(function (item) {
    var text = $(item).attr('data-name');
});

When the code runs the event is firing for all checkboxes, but "text" is undefined when I expect it to be the name data.

Looking for an answer to my method of doing this AND/OR a better way involving skipping the data element all together and getting the name value directly. Thanks for looking.


Solution

  • Try this:

    var text = $(this).data('name');
    

    The first parameter of your change function is the event, not the element itself. Also, jQuery automatically sets the function scope (this) to the element being changed.

    See Documentation