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
}
});
},
....
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>
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.
I'm trying to get prescription details of particular patient and the corresponding result is displayed in modal window. Problem is first result is obtained only on 2nd click. On successive click result of previous data is obtained. Below is my HTML:
<table class="table">
<thead>
<tr class="text-center" style="font-weight: bold">
<td></td>
<td>Name</td>
<td>ID</td>
<td>Age</td>
<td>Registered On</td>
<td>View Prescription</td>
</tr>
</thead>
<tr class="text-center">
<td><input name="name" type="text"></td>
<td><input name="id" type="text"></td>
<td><input name="age" type="text"></td>
<td><input name="reg_on" type="text"></td>
<td>
<button id="view_prescription_from_patient_list" value="register" onclick="view_prescription_from_patient_list(this.value)">
<span class="glyphicon glyphicon-share"></span>
</button>
</td>
</tr>
<div class="modal_show"></div>
function view_prescription_from_patient_list(patient_id) {
var dataString = "get_what=prescription_list_for_patient_list&patient_id=" + patient_id;
$.ajax({
type: "GET",
url: "ajax_get_data.php",
data: dataString,
dataType: "html",
success: function(response) {
$('.modal_show').append(response);
}
})
}
I tried on.click method within javascript but that also has the same problem.
Since you are already using jQuery you can wire the "onclick" event of your button using jQuery.
You need to wire your event handler up like this.
$(document).ready(function() {
$('#view_prescription_from_patient_list').on('click', function(e) {
e.preventDefault();
var patientId = $(this).parent().parent().find('input[name=id]').val();
// do your ajax call here...
});
});
You are passing a value of "register" (this.value from the button clicked).
Instead use jQuery to connect and handler the click event (delete the inline onclick handler).
e.g.
$('#view_prescription_from_patient_list').click(function(){
var patient_id = $(this).closest('tr').find('[name=id]').val();
var dataString = "get_what=prescription_list_for_patient_list&patient_id=" + patient_id;
$.ajax({
type: "GET",
url: "ajax_get_data.php",
data: dataString,
dataType: "html",
success: function(response) {
$('.modal_show').append(response);
}
})
}
});
This will fetch the patent-id from the name="id" TD (which presumably has the ID value - but not shown in your example HTML).
If your code does not follow the DOM elements it references you will also need to wrap it in a DOM ready handler:
$(function(){
// Your code here
});
Note: $(function(){ is just a shortcut for $(document).ready(function(){
Code with jquery on.('click' and you can get patient_id from the parent td
Like $(this).parent().parent().find('input[name=id]').val();
This code may help you to understand
$('#view_prescription_from_patient_list').on('click',function(){
var patientId = $(this).parent().parent().find('input[name=id]').val();
var dataString = "get_what=prescription_list_for_patient_list&patient_id="+patientId;
$.ajax(
{
type:"GET",
url:"ajax_get_data.php",
data:dataString,
dataType:"html",
success:function(response)
{
$('.modal_show').append(response);
}
}
)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
<thead>
<tr class="text-center" style="font-weight: bold">
<td></td>
<td>Name</td>
<td>ID</td>
<td>Age</td>
<td>Registered On</td>
<td>View Prescription</td>
</tr>
</thead>
<tr class="text-center">
<td><input name="name" type="text"></td>
<td><input name="id" type="text"></td>
<td><input name="age" type="text"></td>
<td><input name="reg_on" type="text"></td>
<td><button id="view_prescription_from_patient_list" value="register" ><span class="glyphicon glyphicon-share"></span></button></td>
</tr>
You're reading wrong value as pointed out in previous answers.
I'd suggest also to use Unobtrusive JavaScript
$( document ).ready(function(){
$('#view_prescription_from_patient_list').on('click', function(){
var patient_id = $('[name="id"]', $(this).closest('tr')).val(),
dataString = "get_what=prescription_list_for_patient_list&patient_id="+patient_id;
$.ajax({
// ...
});
});
});
If you really need to stick to onclick attribute for some reason (althought you shouldn't), pass the button to the method:
<button id="view_prescription_from_patient_list" value="register" onclick="view_prescription_from_patient_list(this)">
<span class="glyphicon glyphicon-share"></span>
</button>
and then in JS:
function view_prescription_from_patient_list(btn) {
var patient_id = $('[name="id"]', $(btn).closest('tr')).val(),
dataString = "get_what=prescription_list_for_patient_list&patient_id=" + patient_id;
$.ajax({
// ...
});
}
I have a table and one search fields, based on what is entered in the search fields the contents of the table are refreshed and if nothing is entered in the search fields the full table is loaded. Here when the user clicks on Go button the ajax call is made.
Currently, I have two jsp as below:
MAIN JSP
<script type="text/javascript">
$(document).ready(function() {
$( "#go-user" ).click(function() {
var userId = $('#usrId').val();
alert(userId);
$.ajax({
url: 'popUserSelect', // action to be perform
type: 'POST', //type of posting the data
data: { userId: userId }, // data to set to Action Class
dataType: 'html',
success: function (html) {
alert(html);
$('#load-user').html(html);
//document.getElementById("leftDiv").innerHTML=html; //set result.jsp output to leftDiv
},
error: function(xhr, ajaxOptions, thrownError){
alert('An error occurred! ' + thrownError);
}
});
return false;
});
});
</script>
<s:form theme="simple">
User Id : <s:textfield name="userId" id="usrId" theme="simple"/>
<s:submit action="popUserSelect" key="Go"></s:submit>
</s:form>
<div id="load-user">
<table width="100%">
<thead>
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<s:iterator value="userSupList" >
<tr>
<td><input type="radio" class="RadioButton" name="userRadio" value='<s:property value="USR_AMLUSERNAME"/>' /></td>
<td><s:property value="USR_AMLUSRID"/></td>
<td><s:property value="USR_AMLUSERNAME"/></td>
<td><s:property value="USR_ROLEID"/></td>
<td><s:property value="USR_LOCATIONID"/></td>
</tr>
</s:iterator>
</tbody>
</table>
</div>
<input type="button" value="Submit" onclick="buttonClick('SubmitUser')"/>
<input type="button" value="Cancel" onclick="buttonClick('Close')"/>
Refresh Jsp:
<table width="100%">
<thead>
<tr>
<th>Select</th>
<th>ID</th>
<th>Name</th>
<th>Role</th>
<th>Location</th>
</tr>
</thead>
<tbody>
<s:iterator value="userSupList" >
<tr>
<td><input type="radio" class="RadioButton" name="userRadio" value='<s:property value="USR_AMLUSERNAME"/>' /></td>
<td><s:property value="USR_AMLUSRID"/></td>
<td><s:property value="USR_AMLUSERNAME"/></td>
<td><s:property value="USR_ROLEID"/></td>
<td><s:property value="USR_LOCATIONID"/></td>
</tr>
</s:iterator>
</tbody>
</table>
Is there any way that I can avoid using two jsp for refreshing and refresh the jsp on the same main jsp itself?
You have to give your table an ID:
<table width="100%" id="myTable">
...
</table>
And adapt your AJAX call:
$.ajax({
url: 'originalPage', // use original page here
type: 'POST',
data: { userId: userId },
dataType: 'html',
success: function (html) {
// get the content of #myTable from the AJAX result
var tableContent = $("#myTable", html).html();
// set the content of #myTable to the result of the AJAX call
$('#myTable').html(tableContent);
},
error: function(xhr, ajaxOptions, thrownError){
alert('An error occurred! ' + thrownError);
}
});
jQuery can take the target to use as second parameter, which is used in $("#myTable", html). This way, it does not search the current document for #myTable, but the document returned from the AJAX call.
The disadvantage of this that the whole original page needs to be loaded through AJAX, although only one minor part of it is used.
I have code that is generated by passing data from an ajax call to an ActionView method in my controller. I can only access that data when the ajax call returns. The area where I am trying to display my data is not getting refreshed so I added it to my PartialView to return back to the page div I created. My issue is that I have a placeholder of exactly the same small table so that the page does not look goofy before the user submits what they need to to call the ajax request. My issue is that the button I have in the placeholder area and area that I have displaying back are not working correctly. I think what is happening is that the javascript is getting confused by the two areas having the same information, but changing the names/ids doesn't seem to fix it. Here is my code. (I also need the placeholder table to be functional before it is hidden)
This is in the main page:
<tr>
<td>Comments: #Html.TextBox("comments2", comment)</td>
<td></td>
</tr>
<tr>
<td style="vertical-align: middle;">Booking#:#Html.TextBox("bookNum2", bookNum)</td>
<td><input id="saveOrder2" type="button" value="Save Order2" onclick="saveOrder2(true)" /></td>
</tr>
<tr>
<td style="vertical-align: middle;">Ship Date:#Html.TextBox("shipDate2", shipDate)</td>
<td>
<input id="Build" type="button" value="Build Load" /> </td>
</tr>
</table>
In the PartialView page I have this:
<tr>
<td>Comments: #Html.TextBox("comments", comment)</td>
<td></td>
</tr>
<tr>
<td style="vertical-align: middle;">Booking#:#Html.TextBox("bookNum", bookNum)</td>
<td><input id="saveOrder" type="button" value="Save Order" onclick="saveOrder(true)" /></td>
</tr>
<tr>
<td style="vertical-align: middle;">Ship Date:#Html.TextBox("shipDate", shipDate)</td>
<td>
<input id="Build" type="button" value="Build Load" /></td>
</tr>
</table>
Then the javascript function I am using:
function saveOrder(isSave)
{
var comments = document.getElementById("comments2").value;
var bookNum = document.getElementById("bookNum2").value;
var shipDate = document.getElementById("shipDate2").value;
var itemList = grabSaveItems();
//alert(itemList.toString());
var request = $.ajax(
{
type: "POST",
url: "/Home/saveOrder",
data: "itemList=" + itemList+"&isSave="+isSave+"&comments="+comments+"&bookNum="+bookNum+"&shipDate="+shipDate,
success: function (itemList) {
}
});
request.done(function () {
if (isSave == true)
{
alert("The Order Was Saved");
}
});
request.fail(function (Check, textStatus) { alert("Request failed: " + textStatus); });
}
So based on the order number I add the information I need to the Model and then return my PartialView to display what I need.
When I click Save Order after this ajax call is made I get the following runtime error:
Microsoft JScript runtime error: Member not found. Which occurs just after the call to save Order, the debugger points to the line just after this function, not sure what that means. Any help would be appreciated.
Ok, I knew it was something dumb. It looks like Javascript gets freaky when you assign the id of the input the same name as your function so it doesn't know what to do/call.
<td><input id="**saveOrder"** type="button" value="Save Order" onclick="**saveOrder**(true)"/></td>