I have a small application in MVC4. It has a grid and every row has two things.
1) ID
2) Button
When user click on a button I need to invoke a javascript function passing ID as an parameter. How can I do this in MVC. I can eaisly do thin in case of . Please help
Below is my code.
#model IEnumerable<Models.Asset>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Id
</th>
<th>
Show
</th>
</tr>
#foreach (var item in Model) {
<tr>
<td width="80">
#item.Id
</td>
<td>
<button class="btnView" onclick="myfunction(#item.someProperty)">Show</button>
///How can I pass #item.someProperty as an parameter to click handler?
</td>
</tr>
}
</table>
<div id="imageDisplay">
<p>
</p>
</div>
#section scripts{
<script type="text/javascript">
$(function () {
$('#imageDisplay').dialog({
autoOpen: false
});
$('.btnView').click(function () {
alert('ok');
//How can I get id as an parameter to this function?
});
});
</script>
}
Firstly just remove onclick handler from the button(You don't need it as you are handling click event with jquery)
Try this :
HTML :-
<td>
<button class="btnView" data-prop="#item.someProperty">Show</button>
</td>
JQUERY :-
$('.btnView').click(function () {
var prop = $(this).attr('data-prop');
alert(prop);
});
OR
$('.btnView').click(function () {
var prop = $(this).data('prop');
alert(prop);
});
OR(if you don't want to add data-prop on button then you can follow below answer,Just catch 'Id' which is there in td of your table)
$('.btnView').click(function () {
var id = $(this).closest('tr').find('td').eq(0).text();
alert(id);
});
Remove the onclick handler from the button (you don't have a function called myfunction)
Since you already have the ID value in the previous column, you can get it using
$('.btnView').click(function () {
var id = $(this).closest('tr').children('td').eq(0).text();
});
Related
Recently, I installed the Datatable library in my Asp.net app, and is very useful!
I wanted one of my Datatables to have a "Checkbox all" that when pressed, would mark all the existing checkboxes in the current rows of the table which are filtered, and aslo I wanted that all of those checkboxes were part of a group with a name attribute assigned. And when searching, I found a already-made Script that does just what I want!
This one: https://jsfiddle.net/gyrocode/abhbs4x8/
but I'm having a hard time trying to understand how the heck I should adapt this script to my app environment. Since I use a Model instead of ajax/json?, and unlike the link code, I want to put a checkbox manually in each td row of my table, instead of making them appear in an empty "td", as the link code does (thing I don't understand exactly how the code does it).
Can someone help me adapt the code made by gyrocode too my app? Thank you very much in advance.
My view code without gyrocode's jquery datable script:
#model IEnumerable<Co.Models.Com>
<div class="container">
<div class="card level-3">
<h3>List</h3>
<link rel="stylesheet" type="text/css" href="~/DataTables/datatables.min.css" />
<div>
<table class="table table-sm table-bordered select" id="tabla">
<thead class="thead-dark">
<tr>
<th><input name="select_all" value="1" type="checkbox"></th>
<th>
<div>Nomb</div>
</th>
<th>
<div>Fech</div>
</th>
<th>
<div>AAA</div>
</th>
<th>
<div>Tuuu</div>
</th>
<th>
<div>Hor</div>
</th>
<th>
<div>Mino</div>
</th>
<th><div></div></th>
<th>
</th>
<th><div></div></th>
</tr>
</thead>
<tbody>
#foreach (var item in Model)
{
<tr>
<td><input name="group" value=#item.Id type="checkbox">
</td>
<td>
#Html.DisplayFor(modelItem => item.Nom)
</td>
<td>
#Html.DisplayFor(modelItem => item.Fech)
</td>
<td>
#Html.DisplayFor(modelItem => item.Aombr)
</td>
<td>
#Html.DisplayFor(modelItem => item.Tip)
</td>
<td>
#Html.DisplayFor(modelItem => item.Hor)
</td>
<td>
#Html.DisplayFor(modelItem => item.Tooo)
</td>
<td>
<a class="btn btn-sm btn-primary" asp-action="Edit" asp-route-id="#item.Id">
EDIT
</a>
</td>
<td>
<a class="btn btn-sm btn-primary" asp-action="Details" asp-route-id="#item.Id">
DETAILS
</a>
</td>
<td>
<a class="btn btn-sm btn-danger" asp-action="Delete" asp-route-id="#item.Id">
DELETE
</a>
</td>
</tr>
}
</tbody>
</table>
</div>
<script src="~/assets/js/jquery.min.js"></script>
<script type="text/javascript" src="~/DataTables/datatables.min.js"></script>
<script>
$("#tabla").dataTable({
responsive: true,
buttons: [
'excelHtml5',
'csvHtml5',
'pdfHtml5'
],
});
</scrip>
Jquery Datatable: https://datatables.net/download/
(PD: yes, I tried to just change my table Id from "tabla" to "example", but that wasn't enough to make the code work)
For how to apply gyrocode's code to your code,you could check the following code.And be sure change $("#tabla").dataTable({}) to $("#tabla").DataTable({}):
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.js"></script>
<script>
function updateDataTableSelectAllCtrl(table) {
var $table = table.table().node();
var $chkbox_all = $('tbody input[type="checkbox"]', $table);
var $chkbox_checked = $('tbody input[type="checkbox"]:checked', $table);
var chkbox_select_all = $('thead input[name="select_all"]', $table).get(0);
// If none of the checkboxes are checked
if ($chkbox_checked.length === 0) {
chkbox_select_all.checked = false;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If all of the checkboxes are checked
} else if ($chkbox_checked.length === $chkbox_all.length) {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = false;
}
// If some of the checkboxes are checked
} else {
chkbox_select_all.checked = true;
if ('indeterminate' in chkbox_select_all) {
chkbox_select_all.indeterminate = true;
}
}
}
$(document).ready(function () {
// Array holding selected row IDs
var rows_selected = [];
var table = $("#tabla").DataTable({
responsive: true,
buttons: [
'excelHtml5',
'csvHtml5',
'pdfHtml5'
],
});
// Handle click on checkbox
$('#tabla tbody').on('click', 'input[type="checkbox"]', function (e) {
var $row = $(this).closest('tr');
// Get row data
var data = table.row($row).data();
// Get row ID
var rowId = data[0];
// Determine whether row ID is in the list of selected row IDs
var index = $.inArray(rowId, rows_selected);
// If checkbox is checked and row ID is not in list of selected row IDs
if (this.checked && index === -1) {
rows_selected.push(rowId);
// Otherwise, if checkbox is not checked and row ID is in list of selected row IDs
} else if (!this.checked && index !== -1) {
rows_selected.splice(index, 1);
}
if (this.checked) {
$row.addClass('selected');
} else {
$row.removeClass('selected');
}
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle click on table cells with checkboxes
$('#tabla').on('click', 'tbody td, thead th:first-child', function (e) {
$(this).parent().find('input[type="checkbox"]').trigger('click');
});
// Handle click on "Select all" control
$('thead input[name="select_all"]', table.table().container()).on('click', function (e) {
if (this.checked) {
$('#tabla tbody input[type="checkbox"]:not(:checked)').trigger('click');
} else {
$('#tabla tbody input[type="checkbox"]:checked').trigger('click');
}
// Prevent click event from propagating to parent
e.stopPropagation();
});
// Handle table draw event
table.on('draw', function () {
// Update state of "Select all" control
updateDataTableSelectAllCtrl(table);
});
});
</script>
I'm trying to write a function in jQuery which is going through all table rows and searches for hidden field values by specific hidden control ID "hdnIsEmpty", the problem is that I don't know how to do it by this hidden control ID because there are other hidden controls which are not necessarily to touch...
Maybe there is some other way to get what I wan't, but here is my unsuccessful try/approach and the only one I know:
<udc:Repeater ID="repDetailedInformation" runat="server" DataSource='<%# Eval("DetailsInformation") %>'>
<table id="tblDetails">
<tbody>
<tr>
<td>
BLA-BLA-BLA Information
</td>
</tr>
<tr>
<td>
<udc:HiddenField ID="hdnIsEmpty" runat="server" Value='<%#Eval("IsEmpty") %>' />
</td>
</tr>
<tr>
<td>
<udc:HiddenField ID="hdnBlaBla" runat="server" Value='<%#Eval("BlaBla") %>' />
</td>
</tr>
<tr>
<td>
BLA-BLA-BLA Information
</td>
</tr>
</tbody>
</table>
and jQuery:
<script type="text/javascript">
$(document).ready(function () {
function getHiddenBoolean(name) {
var selector = 'input:hidden[name$="' + name + '"]';
var field = $(selector);
return (field != null && field.length > 0) ? field.val().toLowerCase() == "true" : false;
};
var filteredRows = $('#tblDetails tr td').filter(function () {
return $(this).find('#hdnIsEmpty');
});
$.each(filteredRows, function () {
var isEmpty = getHiddenBoolean(filteredRows);
});
})
The first issue you have is that ASP.Net Webforms changes the id of all runat="server" elements at runtime, so you cannot select by them. Even if you could, in this instance you would have duplicates, which is invalid. Instead you could add a class to those elements to identify them.
<tr>
<td>
<udc:HiddenField ID="hdnIsEmpty" runat="server" class="hiddenfield" Value='<%#Eval("IsEmpty") %>' />
</td>
</tr>
From there you can just loop over that class selector, like this:
$(document).ready(function () {
$('#tblDetails tr td .hiddenfield').each(function() {
if ($(this).val().toLowerCase() == 'true') {
// do something here...
}
});
});
If you are unable to add a class attribute on the control, you could instead make the selector more generic:
$(document).ready(function () {
$('#tblDetails tr td input:hidden:first').each(function() {
if ($(this).val().toLowerCase() == 'true') {
// do something here...
}
});
});
After taking into account the ASP.NET issue mentioned above, another alternative would be:
$(document).ready(function (){
var $hidden = $('.tableClass input.hiddenTouchableElements');
$hidden.each(function() {
if ($(this).val().toLowerCase() == 'true') {
// do something here...
}
});
});
Brain ache.
I have a timer that dynamically adds row to a table. I want an event to fire
when the user clicks on one of the dynamically added rows.
I'm tagging each for with a class of "PortletTableUseButton" and using the .on("click") but it doesn't work.
$('.PortletTableUseButton').on("click", function () {
alert($(this));
});
setInterval(function () { addRow(); }, 2000);
var counter = 2042;
function addRow() {
counter++;
var myRow = "<tr class='PortletTableUseButton'><td>BLOCK-" + counter + "</td><td>Location A</td><td >Use</td></tr>";
$("#Portlet #content tr:last").after(myRow);
}
<div id="Portlet" style="position:absolute; top:500px;left:500px; height:200px;">
<div id="content" style="height:80%;">
<table id="PortletTable">
<tr>
<td>File Name</td>
<td>Location</td>
<td>Action</td>
</tr>
</table>
</div>
</div>
You aren't using event delegation correctly. Try this:
$(document).on('click', '.PortletTableUseButton', function () { ... });
http://learn.jquery.com/events/event-delegation/
Alternatively, run your click function each time you add a row.
I have two anchors and two tables, upon clicking anchor 1, I want table1 to appear and on clicking anchor2 table 1 must be closed and table 2 should appear.
My code in JavaScript for toggling between show and hide:
function setTable(what) {
if (document.getElementById(what).style.display == "block") {
document.getElementById(what).style.display = "none";
}
else if (document.getElementById(what).style.display == "none") {
document.getElementById(what).style.display = "block";
}
}
My two anchors:
<td>
I am
</td>
<td>
Photo
</td>
My two table:
<table id="aboutdialog" title="Me mE me!!" style="display:none;" >
<table width="100%" id="stab" style="display:none;width:58%;height: 60%;">
Now it works for me like, on clicking the anchor1 for the first time it shows table 1 and on second click hides table1. Same for anchor2.
But I want upon clicking anchor1 to close table 2 if opened and display table1 alone vice versa for anchor2.
Without jQuery
<td>
I am
</td>
<td>
Photo
</td>
then
function setTable(what, second) {
if (document.getElementById(what).style.display == "block") {
document.getElementById(what).style.display = "none";
} else if (document.getElementById(what).style.display == "none") {
document.getElementById(what).style.display = "block";
document.getElementById(second).style.display = "none";
}
}
Demo: Fiddle
A jQuery solution might look like
<table>
<tr>
<td>
<!--Add a class trigger to the anchor elements-->
I am
</td>
<td>
<!--Add a class trigger to the anchor elements-->
Photo
</td>
</tr>
</table>
<!--Add a class target to the tables elements-->
<table id="aboutdialog" title="Me mE me!!" style="display:none;" class="target">
<tr>
<td>1</td>
</tr>
</table>
<!--Add a class target to the tables elements-->
<table width="100%" id="stab" style="display:none;width:58%;height: 60%;" class="target">
<tr>
<td>2</td>
</tr>
</table>
then
//dom ready handler
jQuery(function () {
var $targets = $('.target');
$('.trigger').click(function () {
var id = $(this).attr('href');
//hide all other target elements
$targets.not(id).hide();
//toggle the display of current element
$(id).toggle()
})
})
Demo: Fiddle
Just replace the function
function setTable(what){
if(what=="aboutdialog"){
document.getElementById("aboutdialog").style.display="block";
document.getElementById("stab").style.display="none";
}
else if(what=="stab"){
document.getElementById("aboutdialog").style.display="none";
document.getElementById("stab").style.display="block";
}
}
You can do something like this:
$('#iam').click(function() {
$(this).closest('#aboutdialog').show().siblings('#stab').hide();
});
$('#photo').click(function() {
$(this).closest('#stab').show().siblings('#aboutdialog').hide();
});
Try using jquery
$(document).ready(function($) {
$('#iam').click(function(){
$('#aboutdialog').show();
$('#stab').hide();
});
$('#photo').click(function(){
$('#stab').show();
$('#aboutdialog').hide();
});
});
live example is here >>
Simple with the jquery library :
$('#iam').click(function(){
$('#aboutdialog').show().siblings('table').hide();
});
$('#photo').click(function(){
$('#newdialog').show().siblings('table').hide();
});
html
I am</td>
<td>Photo</td>
<table id="aboutdialog" title="Me mE me!!" style="display:none;" >
<tr><th>abc</th></tr>
</table>
<table id="newdialog" title="Me mE me!!" style="display:none;" >
<tr><th>yaskjd</th></tr>
</table>
$(document).ready(function() {
var options = {'iam': 'aboutdialog', 'photo': 'stab'};
$('#iam, #photo').on('click', function() {
$('#aboutdialog, #stab').hide();
$('#' + options.($(this).attr('id'))).show();
});
});
I have the following code:
$("#Table1 tbody").children().each(function(e){
$(this).bind('click',
function(){
// Do something here
},
false)
});
The Table1 html table has 2 columns; one for Names and one for a <button> element.
When I click on a table row, it works fine. When I click on the button, the button code fires; however, so does the row code.
How can I filter the selector so the button doesn't trigger the parent element's click event?
This is what you want.
It's stopPropogation that will stop the parents.
<table>
<tr>
<td>The TD: <input type="button" id="anotherThing" value="dothis"></td>
</tr>
</table>
<div id="results">
Results:
</div>
<script>
$(function() {
$('#anotherThing').click(function(event) {
$('#results').append('button clicked<br>');
event.stopPropagation();
});
$('td').click(function() {
$('#results').append('td clicked<br>');
});
});
</script>
Here's a link to an example of it working as well:
http://jsbin.com/uyuwi
You can tinker with it at: http://jsbin.com/uyuwi/edit
You could also do something like this:
$('#Table1 tr').bind('click', function(ev) {
return rowClick($(this), ev);
}); //Bind the tr click
$('#Table1 input').bind('click', function(ev) {
return buttonClick($(this), ev);
}) //Bind the button clicks
function rowClick(item, ev) {
alert(item.attr('id'));
return true;
}
function buttonClick(item, ev) {
alert(item.attr('id'));
ev.stopPropagation();
return true;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="Table1">
<tbody>
<tr id="tr1">
<td>
The TD: <input type="button" id="button1" value="dothis" />
</td>
</tr>
<tr id="tr2">
<td>
The TD: <input type="button" id="Button2" value="dothis" />
</td>
</tr>
</tbody>
</table>
Is it possible to remove the button code and just run the row code, therefore kind of using event bubbling.
Another couple options:
can you add a class to the TD that has the button in it and in the selector, do '[class!="className"]'
maybe try event.preventDefault(). You can see it being used here. this way you can prevent the default action that is triggered when the button is clicked, although I'm not sure if it will completely prevent the bubbling.