How to access a complex object comming from a datatable cell in JQuery/Javascript
Ad
I have a list of Record objects for the view model (of a Microsoft MVC view) that has the following variables:
Variable1 of string type
Variable2 of int type
...
I have a razor view for the Record object with a table like the following:
<table id="MyTable">
<thead>
<tr>
<th class="col1" id="Column1">Column1</th>
<th class="col2" id="Column2">Column2</th>
<th class="col3" id="Column3">Column3</th>
</tr>
</thead>
<tbody>
@foreach (Record currentRecord in ListOfRecords) {
<tr>
<td class="col1">X</td>
<td class="col2">Y</td>
<td class="col3">@currentRecord</td>
</tr>
}
</tbody>
</table>
Then in my JQuery:
$(document).ready(function () {
function displayData(datainput) {
alert(datainput.Variable1)
}
var oTable = $('#MyTable').DataTable({
"oLanguage": { "sSearch": "Search all columns:" },
"sScrollY": "200px",
"bPaginate": false
});
$('#MyTable tbody').on('click', 'td', function () {
var rowIndex = oTable.cell(this).index().row;
var theData = oTable.cell(rowIndex,2).data();
displayData(theData)
});
});
the idea is to display Variable1 from the record object of that specific row the user clicked on as an alert text, specifically in that displayData function. But I am unable to get to that variable in the displayData function. the alert displays undefined instead of the value of Variable1. Is there a specific way that I need to pass the parameter? I'm new at JavaScript/JQuery/Razor views so please help if you can.
Thank you.
Ad
Answer
Ad
For those that are interested, got it working using Json, first encode it in the view:
<tbody>
@foreach (Record currentRecord in ListOfRecords) {
<tr>
<td class="col1">X</td>
<td class="col2">Y</td>
<td class="col3">@Html.Raw(Json.Encode(currentRecord))</td>
</tr>
}
</tbody>
Then parse it in the script:
$('#MyTable tbody').on('click', 'td', function () {
var rowIndex = oTable.cell(this).index().row;
var theData = jQuery.parseJSON(oTable.cell(rowIndex,2).data());
displayData(theData)
});
Ad
source: stackoverflow.com
Related Questions
Ad
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad