Trying to show "Product Added!" message to the right of the row where the user selected 'Add'. The way I have it right now is:
var addToCart = function (idFromButton) {
$.ajax({
type: "POST",
data: { prodID: idFromButton },
url: '#Url.Action("Add", "ShoppingCart")',
success: function (data)
{
$('#BadgeIcon').html(data).fadeOut(1).fadeIn('fast');
$('.fakeLink-' + idFromButton).text("Product Added!").css("color", "green").fadeIn(600).fadeOut("slow");
}
});
}
which changes the 'Add' button green and fades it away.
I have also tried creating a new row element to the right of the 'Add' column and adding the message there. It works, but moves the 'Add' button to the left during the fading animation, not to mention that it permanently removes the border of that last column upon click until page is refreshed.
Here is my table:
<table class="table" id="table">
<tr>
<th>
Product Name
</th>
<th>
Price
</th>
<th>
Image
</th>
<th>
Add to Cart
</th>
</tr>
#if (Model.Results.Any())
{
foreach (var item in Model.Results)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.Name)
</td>
<td>
#item.Price.ToString("$0.00")
</td>
<td>
#if (item.ImageFile != null)
{
<img src="#Url.Content(item.ImageFile)" />
}
</td>
<td>
<input id="fakeLink" class="fakeLink-#item.ProductID" type="submit" value="Add" onclick="addToCart(#item.ProductID)" />
</td>
</tr>
}
}
else
{
<tr>
<td colspan="4">No product found.</td>
</tr>
}
</table>
Any help would be greatly appreciated.
Your code looks fine except you need to update the button's value, not text. You may use the val() method.
$('.fakeLink-' + idFromButton).val("Product Added!")
.css("color", "green").fadeIn(600).fadeOut("slow");
Also, i see you have duplicate id values for your button's inside the loop. Your id's should be unique. Actually you do not really need an Id for this case. You can simplify your code with unobutrusive javascript like this
<td>
<input class="addBtn" data-product="#item.ProductID" type="submit" value="Add" />
</td>
and listen to the click event of this type of button (button with addBtn css class) and you can use $(this) as the reference of clicked button.
$(function() {
$(".addBtn").click(function(e) {
e.preventDefault();
var _this = $(this);
$.ajax({
type: "POST",
data: { prodID: _this.data("product") },
url: '#Url.Action("Add", "ShoppingCart")',
success: function (data) {
_this.val("Product Added!").css("color", "green").fadeIn(600)
.fadeOut("slow");
}
});
});
});
EDIT : If you want to keep the Add button intact, but want to show a message next to that, you can do this.
success: function (data) {
var msg = $("<span />").html("Product added").css("display","none");
msg.appendTo(_this.parent()).fadeIn(500).fadeOut("slow");
}
You may apply additional css styles to the message span as needed.
Related
I have a ViewModel with a parameter List. In the View, the user should be able to add or remove from that list such that the added or removed users are reflected in the POST for that parameter. In JQuery, after clicking an "Add" button, an ajax call returns a UserModel variable, but a simple .append doesn't add to the list.
The other questions I've seen on this issue deal with Partial Views, but this situation updates the table of UserModel without needing a Partial View. It seems like there should be an easy way to do this. Does anyone know how to add the returned UserModel to the List in JQuery so that the List will be returned to the Post with the added models?
<script>
$("#bUser").on('click', function () {
var $addedRecipient = $("#AddedRecipient");
if ($addedRecipient.val() != null && $addedRecipient.val() != "") {
$.ajax({
type: "GET",
url: '#Url.Action("GetFullRecipient", "Message")',
data: { CompanyID: $("#CompanyID").val(), Employee: $addedRecipient.val() },
success: function (data) {
$("#Recipients").append(data);//Not adding to Recipients (Model.List<UserModel>) - is there a simple solution like this?
var bRow = $('<tr></tr>'),
bCell = $('<td style="display:none"></td>').append(data.UserID);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserFirstName);
bRow.append(bCell);
bCell = $('<td align="center"></td>').append(data.UserEmail);
bRow.append(bCell);
bCell = $('<td align="center"><input type="button" class="btn btn-info removeRecipient" value="Remove"></td>');
bRow.append(bCell);
$("#bTable tbody").append(bRow);//Works with returned data
$addedRecipient.val("");
},
error: function () {
alert("Recipient could not be added.");
}
});
}
});
</script>
this code worked perfect for me, you just have to go through this list, obviously you have to put the #model directive and a type list Recipient.
#model List<...Models.Recipient>
<input type="button" id="btnAdd" class="btn btn-primary" value="Add"
onclick="myfunction()"/>
<script>
function myfunction() {
$.ajax({
type: 'GET',
contentType:"application/json; charset=utf-8",
url: '#Url.Action("GetFullRecipient","Message")',
data: { CompanyID: $("#CompanyID").val(), Employee:
$addedRecipient.val()},
success: function (response) {
$("#containerData").html(response);
},
error: function (result) {
alert(result);
}
});
}
</script>
<div id="containerData">
<table class="table table-striped table-hover table-bordered">
<thead>
<tr>
<th>Id</th>
<th>Desc_Prod</th>
<th>Cantidad</th>
</tr>
</thead>
<tbody>
#if (Model != null)
{
foreach (var item in Model)
{
<tr>
<td>#item.UserID</td>
<td>#item.UserFirstName</td>
<td>#item.UserEmail</td>
<td><a class="btn btn-danger" href="#Url.Action("DeleteRow","Message", new {item.UserID})">Delete</a></td>
</tr>
}
}
</tbody>
</table>
</div>
The answer here followed the link in freedomn-m's comment. Iterate through the Razor table using a for loop, then use a HiddenFor with the model parameter's ID and a CheckBoxFor as the model parameter's selecting field, and have a submit button with a unique name and value. When a button input is clicked and the value fits a given string, loop through the model and add a user that's not there or subtract a user that is there and return to the View.
<div class="row">
<div class="col-lg-12">
<table class="table table-bordered" id="bTable">
<thead>
<tr>
<th style="display:none"></th>
<th style="display:none"></th>
<th class="text-center">Recipient</th>
<th class="text-center">E-mail</th>
<th class="text-center">Select</th>
</tr>
</thead>
<tbody>
#if (Model.Recipients.Any())
{
for (var i = 0; i < Model.Recipients.Count; i++)
{
<tr>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientUserID)</td>
<td style="display:none">#Html.HiddenFor(m => m.Recipients[i].RecipientCorporateID)</td>
<td align="center">#Model.Recipients[i].RecipientName</td>
<td align="center">#Model.Recipients[i].RecipientEmail</td>
<td align="center">#Html.CheckBoxFor(m => m.Recipients[i].RemoveRecipient)</td>
</tr>
}
}
</tbody>
</table>
</div>
</div>
I want to pass text box value and Dropdown selected value as Id which user is entering through jquery POST method from view to controller, but i am not able to pass that values at some point in the code i am missing something but not able to find my mistake, also as there can be multiple records and each records display dropdownlist and textbox differently so how i will know i am using textbox with that particular id and that data from textbox saved in that particular id, i am talking about the role of data-posid to be used in jquery post
My code is as follows
<table class="table">
<tr>
<th>
Item Name
</th>
<th>
Reorder Level
</th>
<th>
Current
</th>
<th>
Outstanding
</th>
<th>
Supplier
</th>
<th>
Quantity
</th>
<th></th>
</tr>
#foreach (var item in Laundrybooking)
{
<tr>
<td>
#Html.DisplayFor(modelItem => item.ItemId)
</td>
<td>
#Html.DisplayFor(modelItem => item.Reorder)
</td>
<td>
#Html.DisplayFor(modelItem => item.Currents)
</td>
<td>
#Html.DisplayFor(modelItem => item.Outstanding)
</td>
<td>
#Html.DropDownList("SIId", null, new { #data_posid="#item.POSId", #class = "form-control", #type = "text"})
</td>
<td>
<input data-posid="#item.POSId" type="text" id="qty" class="qty form-control" placeholder="Quantity" />
</td>
<td>
<button data-posid="#item.POSId" class="addQty btn btn-default"><i class="fas fa-save"></i></button>
</td>
</tr>
}
</table>
$(function () {
$('#SIId').change(function () {
$('.addQty').click(function () {
$.post("#Url.Action("AddQuantity", "PurchaseOrder")", { id: $(this).data('posid'), Qty: $('#qty').val(), Siid: $("select option:selected").val() })
});
});
});
public ActionResult AddQuantity(decimal? Qty, int id, int Siid)
{
var posid = db.SingleOrDefault<POStaging>(id);
if (ModelState.IsValid)
{
posid.Qty = Qty;
posid.SIId = Siid;
db.Update(posid);
}
return RedirectToAction("Index");
}
Please help me with this
Problem is with this code
$('#SIId').change(function () {
$('.addQty').click(function () {
$.post("#Url.Action("AddQuantity", "PurchaseOrder")", { id: $(this).data('posid'), Qty: $('#qty').val(), Siid: $("select option:selected").val() })
});
});
Here you are registering the click event for the button on onChange event of the DropDownList which is fine, but it does not triggers the click event of that button and hence no post call is happening, you need to click on the button to fire the post call. other then that everything looks ok, I have tried this and it is posting the data.
Hope this helps or let me know if I am missing something here...
Happy coding...
I'm using bootstrap table to display a rows from a database, it's MVC ASP.NET and I've put my data in a ViewBag and returned that View with viewbag included as a data to display, so it looks like this:
<div class="row rpad">
<div class="col-md-12">
<div class="z-panel-2">
<div class="oneRow">
<table id="cT">
<thead>
<tr>
<th>
Name
</th>
<th>
Date & time
</th>
<th>
Type
</th>
<th>
Homework done
</th>
<th>
Teacher
</th>
</tr>
</thead>
<tbody>
#foreach (var item in ViewBag.AllClasses)
{
<tr class="class" id="#item.ID">
<td>#item.Date</td>
<td>#item.Type.Name - #item.User_Class.ClassType.NumberOfLessons</td>
<td>
#if (item.HomeWorkDone ?? false)
{
<i class="fa fa-check" aria-hidden="true"></i>
}
</td>
<td>
#item.User.Name
</td>
</tr>
}
</tbody>
</table>
As it's possible to notice I'm looping all data ViewBag.AllClasses and I'm displaying a data as a rows in a table..
When users clicks on a row I'm updating a database with values : homework is readen : true
$.ajax({
url: '#Url.Action("setHomework", "homework")',
type: "GET",
data: { id: id },
And next time user reloads a page, this condition will be executed (as mentioned in a code above):
#if (item.HomeWorkDone ?? false)
{
i class="fa fa-check" aria-hidden="true"></i>
}
Code above means if user has value of true on a homework field, fontawesome icon will be displayed so he will know that he red that homework, but I'm wondering how can I realod content of this bootstrap table after he clicked on that row, so he do not need to reload page to see that mark (font awesome icon) on that row.. ( as a sign that homework is red)
I hope there is another way instead of refreshing whole page/view..
Thanks
I think you can add a success callback to your ajax call. Inside that.. you could append a td to that row.
$.ajax({
url: '#Url.Action("setHomework", "homework")',
type: "GET",
data: { id: id },
success: function (data) {
if (data == "1") { // worked as it should
$(row).find('td:last').after('<td><i class="fa fa-check" aria-hidden="true"></i></td>');
}
}
});
I think a cleaner way will be to have a td there by default and just change the class of icon depending on item.HomeWorkDone. So it would be something like:
$(row).find('.fa-exclamation-circle').addClass('fa-check').removeClass('fa-exclamation-circle');
Also, it is recommended to use HTTP POST for update operations.
I have a table where I need to check data if they already exist in the database. If they do, an alert icon should appear beside the trash icon under Action column on their respective rows and show the appropriate info regarding them.
Currently, I was able to return the ajax data I need if the data I'm comparing already exists in the database. But I don't how I'll show the icons on their respective rows.
Here's my returned data:
{"receive_array":[{"id":"77","batch_id":"45","courier_name":"","vendor_name":"","status":"stored","batch_no":"9","courier_tracking_no":"123"},"",{"id":"126","batch_id":"65","courier_name":"QW12","vendor_name":"Amazon","status":"itemized","batch_no":"18","courier_tracking_no":"QW11"}]}
Here's my Ajax:
$.ajax({
type: "POST",
url: window.base_url+'oss/admin/check_receive_data',
data: $.param($('form#receiving-form').serializeArray()),
dataType : 'JSON',
success: function (response) {
//THIS IS WHERE THE PROCESS SHOULD TAKE PLACE
$.each(response.receive_array, function(index, val) {
});
},
error: function (MLHttpRequest, textStatus, errorThrown) {
console.log("There was an error: " + errorThrown);
}
});
EDIT:
HTML:
<table id="receiving-box-table" class="table table-hover table-bordered table-striped">
<thead>
<tr>
<th>Courier Tracking #</th>
<th>Courier</th>
<th>Vendor</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" form="receiving-form" class="form-control input-sm track_no" name="courier_tracking_no[]" id="courier_tracking_no_1" /></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="courier_name[]" id="courier_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td><input type="text" form="receiving-form" class="form-control input-sm" name="vendor_name[]" id="vendor_name_1" onkeypress="if (event.keyCode == 13) {return false;}"/></td>
<td class="box-action"><button class="btn btn-danger btn-xs clear-data" data-toggle="tooltip" data-placement="right" title="Clear input fields"><span class="glyphicon glyphicon-trash" aria-hidden="true"></span></button></td>
</tr>
</tbody>
</table>
(The rows aside from the first row are dynamically created.)
Any help is highly appreciated. Thanks!
-Eli
You are required 2 loops 1 for the data to be matched and other is the response you got from DB like,
....
success: function (response) {
// Change selectors as per you HTML design
$('table tr').each(function(index){
var ctno=$(this).find('td:first input').val(); // get courier trancking
// check if ctno is present in response array or not
var arr = jQuery.grep(response.receive_array, function( n ) {
return ( n.courier_tracking_no === ctno);
});
if(arr.length){ // if present then show error message
$('span.exists').show(); // let it be hidden by default
}
});
},
....
How to open Modal Dialog from when I click on Button inside table?
function GetAllCountries() {
$('#update_panel').html('Loading Date....');
$('#update_panel').html("<img src='/Pic/ajax-loader.gif'/>")
$.ajax({
url: '/Home/GetCountries',
type: 'GET',
datatype: 'Json',
success: function (data) {
if (data.length > 0) {
var $data = $('<table id="tableItems"> </table>').addClass('table table-responsive table-striped');
var header = "<thead><tr><th>Country ID</th><th>Country</th></tr></thead>";
$data.append(header);
$.each(data, function (i, row) {
var $row = $('<tr/>');
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
});
$('#update_panel').html($data);
}
else {
var $noData = $('<div/>').html('No Data Found!');
$('#update_panel').html($noData);
}
},
error: function () {
alert('Error! Please try again.');
}
});
}
I tried the following code but didn't work
$("#mybtn").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,
});
$("#CreateForm").dialog('open');
})
I think I need something like to reach the button INSIDE the table and add click event of it
$("#Table: Tbody,th,tr").click(function () {
$("#CreateForm").dialog({
autoOpen: false,
modal: false,
width: 500,
height: 500,
When you create the button you also have to set the click event. Any event created before the initialization of an element won't be attached to that specific element. So change your code from this:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$row.append($('<td/>').html("<button class='A' id='mybtn'>Edit</button>"));
$data.append($row);
To this:
$row.append($('<td/>').html(row.CountryId));
$row.append($('<td/>').html(row.CountryName));
$button = $('<button />', {class: 'whatever', id: 'myButton' /* AND SO ON */};
$($button).click(function() {
// CODE TO OPEN THE MODAL
});
$row.append($button);
$data.append($row);
* EDIT *
beanId recover
I hope the code is clear. Anyway Using HTML5 data attribute, you can easily recover the ID of the bean you have to edit. You can also use the action anchor to open a modal, and set to that modal specific values.
$(document).ready(function() {
$('.actionButton').click(function() {
// Recover data-bean-id tag value
var beanId = $(this).data('beanId');
// Do whatever you want
alert('Bean value:' + beanId)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- ** The 'actionButton' anchor can be also used to open a modal -->
<table id="myTable">
<thead>
<tr>
<td>#</td>
<td>FIELD 1</td>
<td>FIELD 2</td>
<td>ACTIONS</td>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="1">ACTION</a></td>
</tr>
<tr>
<td>2</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="2">ACTION</a></td>
</tr>
<tr>
<td>3</td>
<td>AAAAAAA</td>
<td>BBBBBBB</td>
<!-- Setting data-bean-id html5 tag, used to recover the id -->
<td><a class="actionButton" href="#" data-bean-id="3">ACTION</a></td>
</tr>
</tbody>
</table>