I'm creating table like this:
<table>
<tr>
<th>Column</th>
</tr>
#foreach (var item in someList)
{
foreach (var item1 in item)
{
<tr>
<td onclick="myMethod();">#item1.name</td>
</tr>
}
}
</table>
And here is the method which is called when the row is selected:
<script type="text/javascript" language="javascript">
function myMethod() {
var clickedCell = $(this);
alert(clickedCell.text());
}
</script>
But it's not working! How can I get the text from the row/cell which is selected/clicked on?
I also tried:
<script type="text/javascript" language="javascript">
function myMethod() {
alert($(this).html());
}
</script>
and it's giving me null althought the table is full.
I'm inferring from this line that you're using jQuery:
var clickedCell = $(this);
If that's the case, let's take a step back for a moment and separate your JavaScript from your HTML. Instead of this:
<td onclick="myMethod();">#item1.name</td>
which has in-line JavaScript (which is generally frowned upon), try something like this:
<td class="clickableCell">#item1.name</td>
Now it's just markup, which is a bit cleaner. Next you need to attach click events to your rendered cells:
$(document).ready(function() {
$('td.clickableCell').click(function() {
alert($(this).text());
});
});
Now this refers to the element to which jQuery is binding the click event, so it can be easily referenced in the code, as opposed to having to pass a self-reference from the click event being bound within the HTML (which is another approach, but continues down the road of mixing markup with code).
Related
I created a web site in ASP.NET Core MVC, using bootstrap and jquery-ui. The site works well in a desktop.
However in a smartphone, when I want to pick a date with jquery-ui datepicker, the calendar window appears in the wrong position…, outside of the partial window that contains the date input.
My View is:
#using (Html.BeginForm(FormMethod.Post, new { #class = "form-group" }))
{
<table id="ProdTable" class="table">
<tbody id="ProdTable">
#foreach (var p in Model)
{
<tr id="tableRow" data-key="#p.lineid">
<td><input asp-for="#p.paData" type="date"
class="appDatePickClass" autocomplete="off" /></td>
</tr>
</tbody>
</table>
}
<script type="text/javascript">
// setting the Date Picker that I want.
$(document).ready(function () {
$(".appDatePickClass").attr('type', 'text');
$(".appDatePickClass").datepicker({
dateFormat: "yy-mm-dd"
});
});
</script>
Thank you.
Try this work around to adjust position of datepicker after it opens (please adjust position as per your requirement)
<script type="text/javascript" language="javascript">
$(function(){
$("#appDatePickClass").datepicker({ dateFormat:'yy-mm-dd'});
// bind click event and adjust datepicker position.
$(".hasDatepicker").click(function(e){
$("#ui-datepicker-div").css({'top':e.pageY+20,'left':e.pageX-250});
});
});
</script>
and make sure you have :
at top.
i would like to disabled asp=action link after one click
i have a foreach loop to display my book in table in my view
my asp-action for add book in the cart is in the loop but i want to disabled just the book who already in the cart not all books
<a asp-action="AcheterLivre" asp-Controller="Achat" asp-route-id="#item.Isbn" id="disabled" onclick="return myFunction(this);"> Ajouter
i try something with jquery but its dont work well
i tried this
<script>
function myFunction() {
$("#disabled").one("click", function () {
alert("this book is already in the cart");
});
}
i have this function in my class
its verify if the books is in the cart maybe i should use it ?
public bool IsPresent(string isbn)
{
//rechercher si l'isbn correspond a un livre de la liste
AchatLivreViewModel livre = ListeElements.Find(element => element.Isbn == isbn);
if (livre != null)
{
return true;
}
else
{
return false;
}
}
Why not trying this simple approach:
<tbody>
#foreach (var item in Model)
{
<tr>
<td>
#item.Isbn
</td>
<td>
#item.Titre
</td>
<td>
<label class="btn btn-primary" style="padding:0">Add to Cart</label>
</td>
<td>
<label class="btn btn-danger" style="padding:0">Remove From Cart</label>
</td>
</tr>
}
</tbody>
And in your javascript, if you don't want to use Ajax, you can manage your cart items all on client side using an array of objects, Let's name it CartItems:
var CartItems = [];
$('.ADD2CART').click(function () {
if ($(this).closest('tr').hasClass("ExistingInCart")) {
alert('Already in Cart !!');
}
else {
// add this item to the Cart through Ajax or
// local javascript object: e.g.:
CartItems.push({
ISBN: $(this).closest('tr').find('td:eq(0)').text().trim(),
Title: $(this).closest('tr').find('td:eq(1)').text().trim(),
});
$(this).closest('tr').addClass("ExistingInCart");
}
return false; //to prevent <a> from navigating to another address
});
$('.RemoveFromCART').click(function () {
$(this).closest('tr').removeClass("ExistingInCart");
var isbn = $(this).closest('tr').find('td:eq(0)').text().trim();
CartItems = CartItems.filter(x => x.ISBN !== isbn);
return false;
});
Once you need to submit or post the page, you have all the already selected books in CartItems array.
To add this javascript code to your view, choose one of the options:
Put this block at the bottom of your view and copy the above script inside the <script></script> tag:
#section scripts{
<script>
.... copy it here ...
</script>
}
copy the script code inside a newFile.js and add it to your view
<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/newFile.js"></script>
You may decide to bundle this newFile.js
try this:
Ajouter
And your Javascript:
function foo(input) {
if ($(input).attr('yetClickable') === '1') {
$(input).attr('yetClickable', '0');
return true;
}
else {
// this false returning will counteract the effect of click event on the anchor tag
return false;
}
}
Once an Item is removed from the cart, again you need javascript to select that Item by its Id and change the yetClickable attribute back to 1 (in order to be clickable).
Note: This idea above (upon your scenario) works until the page is not reloaded. Otherwise, you need to handle ADD/Remove operations on the Cart through Ajax.
Hope this helps.
I have a Razor for loop:
#foreach (var user in Model.Users)
{
<p class="active-text">Active: #user.LastActive</p>
}
I've just installed moment.js to format this DateTime() date using js.
How can I pass the Razor model into a javascript function? I do have a JS viewmodel for this page, I'm just trying to avoid serializing the entire Model just because I need to apply some JS to a single field. How my viewModel stands right now:
<script type="text/javascript">
$(document).ready(ko.applyBindings(new SubjectVm()));
</script>
I would wrap the date text in another span for later processing:
<p class="active-text">Active: <span class="active-text-date">#user.LastActive</span></p>
Then loop through and apply the formatting, inside document.load:
<script>
$(document).ready(function() {
$(".active-text-date").each(function() {
var date = $(this).text();
var formatted = moment(date).calendar();
$(this).text(formatted);
});
});
</script>
I am attempting to utilise KnockoutJS and MVC 4 in order to display a table with ActionLink definitions in the first column of the table. Displaying the data itself is extremely straight-forward and I'm not having any problem there. The problem I have is in the generation of the ActionLink's.
I have taken a look at Use MVC helpers inside jquery.tmpl templates, but the solution there does not utilise knockout templates and inserting the Url into the model object is not feasible (the app domain model objects used to create the view model will be used extensively through out the application).
The table definition:
<table>
<tbody data-bind="template: { name: 'dmuTableDetail', foreach: tables() }"></tbody>
</table>
(tables is an observable array, hence the parens).
The knockout template definition:
<script id="dmuTableDetail" type="text/html">
<tr>
<td>#Html.ActionLink("Details", "Details", "DMUTableCategory", new { #Id = ??? } )</td>
<td data-bind="text:TableId"></td>
<td data-bind="text:TableName"></td>
</tr>
</script>
The View Model definition:
var PageViewModel = function () {
self = this;
self.tables = ko.observableArray([]);
self.readItems = function () {
self.tables(jQuery.parseJSON('[{"TableId":1001, "TableName":"Table#1"},{"TableId":1002, "TableName":"Table#2"}]'));
}
}
$(document).ready(function () {
vm = new PageViewModel();
self.readItems('');
ko.applyBindings(vm);
});
(the actual code performs an Ajax call to retrieve the data, but the code above also demonstrates the issue).
Regardless of what I replace the ??? with, I am unable to get the value of the TableId field to be inserted into the href.
Any help would be greatly appreciated.
Thankyou.
Thankyou Eric, you got me thinking about an anchor element and binding the href attribute.
It seems the answer is a little easier than expected (it usually is!).
The table definition: (same as original question)
<table>
<tbody data-bind="template: { name: 'dmuTableDetail', foreach: tables() }"></tbody>
</table>
The knockout template definition: (change to the binding of the href attribute).
<script id="dmuTableDetail" type="text/html">
<tr>
<td><a data-bind="attr: { 'href': '#Url.Action("Details", new RouteValueDictionary() { { "Controller", "DMUTableCategory" } } )/' + TableId }">Details</a></td>
<td data-bind="text:TableId"></td>
<td data-bind="text:TableName"></td>
</tr>
</script>?
The View Model definition: (same as original question)
var PageViewModel = function () {
self = this;
self.tables = ko.observableArray([]);
self.readItems = function () {
self.tables(jQuery.parseJSON('[{"TableId":1001, "TableName":"Table#1"},{"TableId":1002, "TableName":"Table#2"}]'));
}
}
$(document).ready(function () {
vm = new PageViewModel();
self.readItems('');
ko.applyBindings(vm);
});
You dont actually need to RootValueDictionary but I've included it so people can see how to change the controller the request is sent to.
Knockout binds completely on the client side, which is after MVC has rendered the HTML for your page and sent it back to the original browser.
If you want your Knockout template to be able to use a URL that is generated on the server, then you'll have to employ some clever strategy similar to the following:
CSHTML:
#{
// create a dummy URL that you can use as a template
string hrefFormat = Url.Action("Details", "DMUTableCategory", new { id = "{ID}" });
}
<script type="javascript">
// a global string (but you can put it where ever you need to)
var _hrefFormat = #Html.Raw(hrefFormat)
<script>
JS:
self.readItems = function () {
self.tables(jQuery.parseJSON('[{"TableId":1001, "TableName":"Table#1"},{"TableId":1002, "TableName":"Table#2"}]'));
// loop through the 'tables' and add a new 'href' property to each for binding
ko.utils.arrayForEach(self.tables(), function(table){
table.href = _hrefFormat.replace("{ID}", table.TableId);
});
}
Your KO Tmpl where you bind the 'href' property of each table object to the a tag's href attribute:
<script id="dmuTableDetail" type="text/html">
<tr>
<td><a data-bind="attr: { 'href': href }">Details</a></td>
<td data-bind="text:TableId"></td>
<td data-bind="text:TableName"></td>
</tr>
</script>
I have a table full of data, upon clicking on any of the record. A jquery ajax function called and get the detailed information for that record and display it in the div associated with the record.
Now i want to show it in a accordion.
Most of time a jquery accordion works like this
$(document).ready(function() {
$('#accordion').accordion();
});
But here i want that my div gets populated first with data then accordion method gets called. Because if accordion() called first then there is nothing for accordion to display as the request for data is still in processing.
My jquery ajax method is like this
$(function () {
$("span.Consignment").click(function () {
var position = 'div#' + this.innerHTML;
var url = "/Tracking/TrackingConsignment?consno=" + this.innerHTML;
$(position).load(url, function() {
$("a.Consignment").accordion();
return false;
});
});
});
This is my code
#foreach (var lst in item.Item2)
{
<a href="#" class="Consignment">
<table class="gridtable">
<a href="#">
<tr>
<td>
<span class="Consignment" href="#">#lst.ConsignmentNo</span>
</td>
<td>#lst.ConsignmentDate
</td>
</tr>
</a>
</table>
</a>
<div id="#lst.ConsignmentNo">
</div>
}
How should i make it work. First data then accordion.
Setup your accordion in the success of the .load.
.load(url,function(){
$("#accordion").accordion();
})