AjS AjS - 1 month ago 12
Javascript Question

get the data associate with cell in Selected event

I am doing a form generator app to be developed in jquery/javascript.
I am using a html table an in order the cell to be selectable I am using jquery 'selectable' api. I have attached some metadata to the cells while initializing the cells and now I want to access that in 'selected' event. But some how it is not accessible.

$("#form_table").selectable({
filter: "td",
selected: function (event, ui) {
populatepropgrid(ui.data("element"));
}
});


ui.data is always undefined in above code. I am new to jquery so sorry for such a easy question.

Answer

You can get the data-element attribute of the selected cell with:

$(ui.selected).data("element")

$("#form_table").selectable({
    filter: "td",
    selected: function (event, ui) {
        console.log("Selected: " + $(ui.selected).data("element"));
    }
});
 td.ui-selecting { background: #FECA40; }
 td.ui-selected { background: #F39814; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.1/jquery-ui.min.js" integrity="sha256-VazP97ZCwtekAsvgPBSUwPFKdrwD3unUfSGVYrahUqU="   crossorigin="anonymous"></script>
<table id="form_table">
    <tr>
        <td class="ui-widget-content" data-element="elem1">Element 1</td>
        <td class="ui-widget-content" data-element="elem2">Element 2</td>
        <td class="ui-widget-content" data-element="elem3">Element 3</td>
    </tr>
    <tr>
        <td class="ui-widget-content" data-element="elem4">Element 4</td>
        <td class="ui-widget-content" data-element="elem5">Element 5</td>
        <td class="ui-widget-content" data-element="elem6">Element 6</td>
    </tr>
</table>

Comments