I want remove classes which are created dynamically using jQuery.
I have a dynamic classes in table like:
"dynamicHeader","record1","record2","record3"
I want to remove all classes class name contain 'record'. Thanks Advance.
via Chebli Mohamed
I want remove classes which are created dynamically using jQuery.
I have a dynamic classes in table like:
"dynamicHeader","record1","record2","record3"
I want to remove all classes class name contain 'record'. Thanks Advance.
I have a html page which contains a table in it and I have add that page into my asp.net project. Now I want freeze the panes(fix 1st five rows as header and 1st column) without modifying the html page..
In that html page the table did not contain 'thead', 'tbody' and 'th' tags.
It just like this...
<table>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
</tr>
</table>
I don't want to add 'th', 'thead' tags to my html page... because I don't want modify my page... I think we may add them and freeze the panes dynamically.....
I have an automcomplete working using the method below. I type in and it returns the user name of the individual I am searching for and it also shows me the ID of the user if I want to. However, what I require is for the FIRST and LAST NAME to show in the input box but the actual value (ID) to be passed when the form is submitted. So how to I get the value of the input type to be the ID but show the drop down as first and last name?
HTML
<input type='search' id='nameSearch' placeholder='Search User' />
SCRIPT
<script>
$(document).ready(function(){
$('#nameSearch').autocomplete({
source:'results.php',
minLength:1,
select: function(event, ui){
// just in case you want to see the ID
var accountVal = ui.item.value;
console.log(accountVal);
// now set the label in the textbox
var accountText = ui.item.label;
$('#nameSearch').val(accountText);
return false;
},
focus: function( event, ui ) {
// this is to prevent showing an ID in the textbox instead of name
// when the user tries to select using the up/down arrow of his keyboard
$( "#nameSearch" ).val( ui.item.label );
return false;
},
});
});
</script>
SQL
include "libs/db_connect.php";
// get the search term
$search_term = isset($_REQUEST['term']) ? $_REQUEST['term'] : "";
// write your query to search for data
$query = "SELECT
ID, NAME, LAST_NAME
FROM
b_user
WHERE
NAME LIKE \"%{$search_term}%\" OR
LAST_NAME LIKE \"%{$search_term}%\"
LIMIT 0,10";
$stmt = $con->prepare( $query );
$stmt->execute();
// get the number of records returned
$num = $stmt->rowCount();
if($num>0){
// this array will become JSON later
$data = array();
// loop through the returned data
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$data[] = array(
'label' => $NAME . " " . $LAST_NAME,
'value' => $ID
);
}
// convert the array to JSON
echo json_encode($data);
}
//if no records found, display nothing
else{
die();
}
previously we used to have fineuploader version called custom, which was a jquery wrapper and we had both azure upload to blob + traditional upload to your server
in the new version 5.2 when I call the fineUploader() method to upload to our own server it gives out errors.
I need some help with how to get a variable from another PHP script to a JQuery in my index.php file.
On my webpage I have the ability to search a database and this is done by the click of a button which performs the search and displays the results in another div on the page.
This part of the webpage work fine.
What I would like to do next is for another button to be able to download a text file with the results of my query. The result is calculated in another PHP file, the same one that displays it.
My JQuery in index.php looks something like:
<script>
$(document).ready(function(){
$("#querySubmitButton").click(function(evt){
evt.preventDefault(); // stops the submit taking place
var myQuery = $('#queryText').val(); // get the query value
$('#container').load('getData.php', { query:myQuery });
});
$("#selectButton").click(function(evt){
evt.preventDefault();
var selectQuery = $( "#selectBox" ).val();
$('#container').load('getData.php', { query:selectQuery });
});
$("#downloadButton").click(function(evt){
alert($result); //Somehow alert the $result variable from my getData.php file, to make sure that I can receive it and perform further things on it so that it is downloaded as a document.
});
});
</script>
As I use the getData.php file for displaying my result in another div, I can't echo $result and use it in JSon?? because that will also be displayed on my webpage, which I of course do not what.
Is this possible somehow?
Thank you for any help. //Ambrose
Here is my code in getData.php if that is of help:
$conn = pg_connect("dbname=xxx user=xxxxxxx password=xxxxxxxx");
if (!$conn) {
die("Error in connection: " . pg_last_error());
}
$query =$_POST['query'];
$result = pg_query($query);
if (!$result) {
echo "Problem with query " . $query . "<br/>";
echo pg_last_error();
exit();
}
else{
if(empty($result)){
echo"Tom";
}
else{
echo "<table class='resultTable'><tr>";
$i=0;
while ($i < pg_num_fields($result))
{
$fieldName = pg_field_name($result, $i);
echo '<td>' . $fieldName . '</td>';
$i = $i + 1;
}
echo '</tr>';
while($row = pg_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $key => $value){
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
}
}
I am developing a SAPUI5 in order to upload files [mainly XML ]. I have implemented the view using XML views within the WebIDE as well as the corresponding JS controller, which is calling an oData service matched with 'create_stream' method then doing the job of reading the file content.
All is working fine but then I cannot receive the response containing the file content [parsed] from the oData back to my js controller.
Here is my ajax call, actually there are two calls but the first one is used to get the necessary security csrf token only.
jQuery.ajax({url : Service1,
type : "GET",
async: false,
beforeSend : function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success : function(data, textStatus, XMLHttpRequest) {
token = XMLHttpRequest.getResponseHeader("X-CSRF-Token");
}
});
$.ajaxSetup({
cache : false
});
jQuery.ajax({
url : service_url,
async : false,
dataType : "text",
cache : false,
data : filedata,
type : "POST",
beforeSend : function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
xhr.setRequestHeader("Content-Type", "application/text;charset=UTF-8");
},
success : function(odata) {
oDialog.setTitle("File Uploaded");
oDialog.open();
document.location.reload(true);
},
error : function(odata) {
oDialog.setTitle("File NOT Uploaded");
oDialog.open();
document.location.reload(true);
}
});
Can anyone find where I am wrong within this flow ?
I think the problem might be in the ajax call, maybe in the parameters or in the way I am getting the data as response from the oData service ?
Or the issue could be whithin the oData create_stream method ?
I am using jquery.tipTip to display text on image’s mouseover but it randomly activates and displays the text when there is no mouseover on the image.
$('.tooltip').tipTip({maxWidth: 'auto', edgeOffset: 5, defaultPosition: 'top', keepAlive: false, activation: "hover"}); [![enter image description here][1]][1]
i have a class disabled in my code, but that class is removed from DOM when i refresh the page.
i have no idea how to check that , the js it's so big so i dont wanna touch and broke something.
so what is happen when i check my DOM i see:
class="btn-color rank"
on my html i inserted disabled but always after load the page the disable class is removed.
class="btn-color rank disabled"
the funniest part is : if i insert a div bellow of that one with the class disable, both will be have the class disable.
i wanna know when the class disable is removed from DOM, someone know can i check that by console?
I'm having strange issue when having absolutely positioned element with Bootstrap tooltip.
Tooltip is not rendered correctly according to parent element, please see fiddle: [http://ift.tt/1VZ7ctd]
When parent element is not positioned absolutely everything is working just fine. Any ideas how to resolve this issue?
Note: I can't set CSS with of absolutely positioned element?
I found this fiddle, and modified it a bit (added controls and pager). Now when you click on prev/next or on pager(1,2,3,etc.) I want to add active class to the current caption.
$('.bxslider').bxSlider({
mode: 'fade',
captions: false,
controls: true,
pager: true,
auto: true,
speed: 1000,
onSlideBefore: function (currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
console.log(currentSlideHtmlObject);
$('.active-caption').removeClass('active-caption');
$(currentSlideHtmlObject).prev().addClass('active-caption')
},
onSlideNext: function (currentSlideNumber, totalSlideQty, currentSlideHtmlObject) {
console.log(currentSlideHtmlObject);
$('.active-caption').removeClass('active-caption');
$(currentSlideHtmlObject).next().addClass('active-caption')
},
onSliderLoad: function () {
$('#bxsliderCaption>ul>li').eq(0).addClass('active-caption')
},
// http://ift.tt/1dFlt6b
});
I am using DataTables plugin with Responsive Table and fixed yScroll and disabling xScroll.
But I am still getting the Horizontal Scrollbar, though I am adding the code like below...
scrollY: 200,
scrollX: false,
Anyhow, I am using Responsive table, why I want to show the Horizontal Scrollbar?
Please refer the code, online example and screenshot below...
CSS
th,td{white-space:nowrap;}
If I remove above css it is working as expected. But I dont want to wrap down the td / th text. This is where I am facing problem :(
jQuery:
$(document).ready(function() {
var table = $('#example').DataTable( {
dom: 'RCT<"clear">lfrtip',
scrollY: 200,
scrollX: false,
columnDefs: [
{ visible: false, targets: 1 }
],
"tableTools": {
"sRowSelect": "multi",
"aButtons": [
{
"sExtends": "print",
"sButtonText": "Print"
}
]
}
});
});
HTML
<table id="example" class="display responsive" cellspacing="0" width="100%">
<thead>
<tr>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Age</th>
<th>Start date</th>
<th>Salary</th>
</tr>
</thead>
<tbody>
<tr>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td>Edinburgh</td>
<td>61</td>
<td>2011/04/25</td>
<td>$320,800</td>
</tr>
.....................
I have a jQuery flot graph that loads the x-axis like so:
xaxis: {
tickColor: 'transparent',
tickDecimals: 0,
ticks: ticks
},
If I set the ticks variable like so it works, and the x-axis contains the 7 dates:
var ticks = [[1,"27/07"],[2,"28/07"],[3,"29/07"],[4,"30/07"],[5,"31/07"],[6,"01/08"],[7,"02/08"]];
console.log(ticks);
However if I generate the variable from an array like so:
var ticks = JSON.stringify(myArray);
console.log(ticks);
It doesn't work, the x-axis contains the numbers 1 - 7.
Here is what the console.log shows:
It looks like my JSON.stringify is correct but I'm not sure what to do! Any ideas? Why is the first console.log entry coloured but the second one not? Is the format incorrect?
I am trying get difference of two time in safari browser .It is working fine in chrome .But on safari I am getting NAN.when I run application I save today date first time.and on second time I run my application I get the difference of save date and now date .it give correct in chrome .but fail in safari why ? here is my code http://ift.tt/1KNZ7nL
var todaydate = new Date();
var datetime = todaydate.getMonth() + 1 + "-" + todaydate.getDate() + "-" + todaydate.getFullYear() + " " + todaydate.getHours() + ":" + todaydate.getMinutes() + ":" + todaydate.getSeconds();
if (localStorage.getItem("getSinkdate") == null || localStorage.getItem("getSinkdate") == '') {
alert('empty')
localStorage.setItem("getSinkdate", datetime);
} else {
var datetimeLocal = window.localStorage.getItem("getSinkdate")
var d1 = new Date(datetime);
var d2 = new Date(datetimeLocal);
alert((d2.getTime() - d1.getTime()) / (1000 * 3600))
alert((d2.getTime() - d1.getTime()) / (1000 * 3600) > 12)
if ((d2.getTime() - d1.getTime()) /(1000*3600)> 12)
{
alert((d2.getTime() - d1.getTime())/ (1000 * 3600));
localStorage.setItem("getSinkdate", datetime);
}
}
I have a link that when clicked should assign a rails variable to a JavaScript variable. The JavaScript is then used to calculate the price. I have the price calculated with a hard coded value at the moment.
in the html I need data-price to be var blankPrice in the js. Any help would be great.
function calculatePrice(){
var blankPrice = 5;
console.log(blankPrice)
var pricePerSide = 3;
var printedSides = 0;
if (frontCanvas) {
var frontCanvasJson = JSON.parse(frontCanvas);
if (frontCanvasJson && frontCanvasJson.objects.length > 0)
printedSides++;
}
if (backCanvas) {
var backCanvasJson = JSON.parse(backCanvas);
if (backCanvasJson && backCanvasJson.objects.length > 0)
printedSides++;
}
var total = blankPrice + (pricePerSide * printedSides);
$('.base-price').text('$' + total);
}
function saveCampaign() {
campaign.front_canvas = frontCanvas;
$.post('/campaigns', campaign);
}
<a
tabindex="-1"
data-original-title="<%= shirt_color.color_name.titleize %>"
class="shirt-color-link"
data-color="#<%= shirt_color.hex %>"
data-price="<%= product.base_price %>"
data-product-id="<%= product.id %>">
<table>
<tr>
<td style="border: 1px solid #DDD" bgcolor="#<%= shirt_color.hex %>"></td>
<td style="padding-left: 10px;"><%= shirt_color.color_name.titleize %></td>
</tr>
</table>
</a>
Problem: As found in kcfinder's definition I am using this link to open kcfinder:
window.open('/kcfinder/browse.php?type=files&dir=files/public&subDir=/PO/'+editId, 'kcfinder_textbox',
', width=800, height=600');
In here, I have modified the URL to also include the subdirectory path so that the URL becomes something like this http://ift.tt/1VZ7aBx .
The subDir part has the directory name to be set to (and created if not exists). In the config.php I already have a directory set to be the root. So if the subDir is provided it will create the subDir inside the root of config.php. Now I would want this subDir to be the new root directory for kcfinder.
So for example if my uploadURL in the config is /var/www/html/web/upload/ the new root for the above URL will become /var/www/html/web/upload/PO/200836/.
Attempt: So far I have been able to successfully create the directory /var/www/html/web/upload/PO/200836/ for the above URL (or any URL) provided. However, the root in kcfinder is still set to /var/www/html/web/upload/. So when I open the kcfinder, the directory gets created internally but the root is still set to the original root from config.php.
I added the following lines to change my root directory to the sub directory I pass through URL:
$this->config["uploadURL"] .= $_GET['subDir'];
$this->config["uploadDir"] .= $_GET['subDir'];
$this->typeDir = $this->config["uploadDir"] ."/files";
$this->typeURL = $this->config["uploadURL"] ."/files";
I have also raised this as an issue on github but no response from there yet. I am assuming the only change I need to do is set the root directory to display to the new directory being created but I am not sure where I am supposed to do this.
Is there a workaround for this?
PS: I am also open to any other web file manager PHP/jQuery solutions which has a way to do this. Using symfony as the framework.
I have a server side code block such as <%Response.Write(...)%> How would i append it dynamically from client side script using jquery?
$("div.items").append('<form action="#" method="POST">');
$(".items form').append('<%Response.Write(...)%>') //???
I tried to write a nav bar with foundation.css, but the sub-menu does not show when mouse move on.
The question is, how can I show the sub-menu of test in this webpage.
I tried to change the visibility, display, z-index, left, but nothing happend.
I have a validator, it has error messages, and my goal is to get only error messages with the field names.
$validator = Validator::make(
array(
'firstField' => Input::get('firstFieldName');
'secondField' => Input::get('secondFieldName');
),
array(
'firstField' => 'required';
'secondField' => 'required';
)
);
if($validator->fails()){
return $validator->messages();
}
So, this piece of code is returning some values to my js file as following
function getErrorMessages(){
//Some UI functions
var myDiv = document.getElementById('messageDivID');
$.post('validationRoute', function(returedValidatorMessageData)){
for(var a in returedValidatorMessageData){
myDiv.innerHTML = myDiv.value + a;
}
}
}
Problem is, the only values i get from post request is like firstField secondField but i'd like to get like firstField is required message. What would be the easiest way ?
Thanks in advance.
I have a text box
<input id="textinput" type="text" name="text_input" value=""/>
and a properly linked (did a console.log in the document ready function and it worked) jquery file
$(document).ready(function()
{
console.log("hi");
});
$( '#textinput' ).keypress(function() {
var tag_text = $('#textinput').val();
console.log("key pressed");
});
As far as I can tell, I'm doing everything properly. However, I am obviously not doing something right.
My goal is to make it so that whenever a letter/character (or any key, really) is pressed with focus on the textinput textbox, an event will trigger.
What am I doing wrong here?
First let me thank @Jasen, he spent 9 days helping me with an issue and it means a lot to me that he took him time to help me. It was this that he was helping me with, but at the last second they decided they wanted to go with AJAX since the contact page uses it and removing items from the cart utilizes it.
Let me get to my issue, I have view (this is MVC 5) that in loop loads all the products of a selected category. I want to use jQuery nd AJAX to add items to the cart. This works great for the first item in the list the first time it is added to the cart.
I imagine my problem is all the buttons have an id of AddToCart and jQuery, the way I have it written can't decide which button is being clicked.
Here is the code for the view
@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>
@{
ViewBag.Title = "Products > Necklaces";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
@Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
<div id="container">
<div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
<div style="color:red" id="ItemAdded"></div>
<div class="scroll">
@foreach (var item in Model)
{
<div class="scroll2">
<div class="itemcontainer">
<table>
<tr>
<td id="@item.Id" class="divId">
<div class="DetailsLink" id="@item.Id"> @Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
<br />
<div id="@item.Id"></div>
<div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
<div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
<div> </div>
<div class="divQuantity"> Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @id = "quantity", @style = "width:50px;", @class = "formTextBox" })</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="AddToCart" class="btn btn-default" id="AddToCart" />
</div>
</div>
<div style="height:15px;"></div>
</td>
</tr>
</table>
</div>
</div>
}
<div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
<br />
</div>
</div>
@*}*@
And here is my jQuery code:
@section scripts {
<script src="~/Scripts/jQuery-jScroll.js"></script>
<script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
<script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript">
//$(function () {
// $('.scroll').jscroll({
// autoTrigger: true
// });
$('.fancybox-thumbs').fancybox({
prevEffect: 'none',
nextEffect: 'none',
closeBtn: true,
arrows: false,
nextClick: false
});
// Document.ready -> link up remove event handler
$("#AddToCart").click(function () {
//first disable the button to prevent double clicks
$("#AddToCart").attr("disbled", true);
$("#AddToCart").prop("value", "Adding...");
$("#ItemAdded").text("");
//now show the loading gif
$("#sending").css("display", "block");
// Get our values
var price = parseFloat($(".divPrice").attr("id"));
var quantity = parseInt($("#quantity").val());
var id = parseInt($(".divId").attr("id"));
$.ajax({
url: "@Url.Action("AddToCartAJAX", "Orders")",
type: "POST",
data: { "id": id, "quantity": quantity, "price": price },
//if successful
success: function (data) {
successfulCall()
},
error: function (data) {
alert(data.Message);
}
});
function successfulCall() {
//enable the send button
$("#AddToCart").attr("disbled", false);
//hide the sending gif
$("#sending").css("display", "none");
//change the text on the button back to Send
$("#AddToCart").prop("value", "Add to Cart");
//display the successful message
$("#ItemAdded").text("Your item has been added to your order.");
//clear out all the values
$("input#quantity").val("0");
}
function errorCall() {
$("#AddToCart").attr("disbled", false);
$("#sending").css("display", "none");
$("#AddtoCart").prop("value", "Add to Cart");
$("#ItemAdded").text(data.message);
}
//alert('Clicked!');
});
//s});
</script>
}
Can someone show me what I am doing wrong here so I can get this working?
EDIT #1
Here is the updated jQuery code:
$(".AddToCart").click(function () {
//first disable the button to prevent double clicks
$(this).prop("disbled", true).prop("value", "Adding...");
$("#sending").css("display", "block");
var td = $(this).closest('td')
//traverse DOM and find relevant element
var price = parseFloat(td.find(".divPrice").prop("id")),
quantity = parseInt(td.find("#quantity").val()),
id = parseInt(td.find(".divId").prop("id"));
$.ajax({
url: "@Url.Action("AddToCartAJAX", "Orders")",
type: "POST",
data: { "id": id, "quantity": quantity, "price": price },
//if successful
success: function (data) {
successfulCall()
},
error: function (data) {
errorCall(data);
}
});
It worked before making the client side changes (granted only once and only for the first item in the list), since I havent changed the server side code what could have gone wrong? EDIT #2
Here is the whole thing in it's entirity
@model IEnumerable<AccessorizeForLess.ViewModels.DisplayProductsViewModel>
@{
ViewBag.Title = "Products > Necklaces";
Layout = "~/Views/Shared/_Layout.cshtml";
}
<link href="~/Content/Site.css" rel="stylesheet" />
<link href="~/Content/jquery.fancybox.css?v=2.1.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-buttons.css?v=1.0.5" rel="stylesheet" />
<link href="~/Content/jquery.fancybox-thumbs.css?v=1.0.7" rel="stylesheet" />
<h2>Products > Necklaces</h2>
<div id="update-message"></div>
<p class="button">
@Html.ActionLink("Create New", "Create")
</p>
@*@using (Html.BeginForm("AddToCart", "Orders", FormMethod.Post))*@
{
<div id="container">
<div id="sending" style="display:none;"><img src="~/Content/ajax-loader.gif" /></div>
<div style="color:red" id="ItemAdded"></div>
<div class="scroll">
@foreach (var item in Model)
{
<div class="scroll2">
<div class="itemcontainer">
<table>
<tr>
<td id="@item.Id" class="divId">
<div class="DetailsLink" id="@item.Id"> @Html.ActionLink(@item.Name, "Details", new { id = item.Id })</div>
<br />
<div id="@item.Id"></div>
<div class="divPrice" id="@item.Price">@Html.DisplayFor(modelItem => item.Price)</div>
<div class="divImg"><a class="fancybox-thumbs" href="@item.Image.ImagePath" title="@item.Image.AltText" data-fancybox-group="thumb"><img src="@item.Image.ImagePath" alt="@item.Image.AltText" title="@item.Image.AltText" /></a></div>
<div> </div>
<div class="divQuantity"> Quantity: @Html.TextBoxFor(modelItem => item.Quantity, new { @style = "width:50px;", @class = "formTextBox quantity" })</div>
<div class="form-group">
<div class="col-md-offset-2 col-md-10">
<input type="button" value="AddToCart" class="btn btn-default AddToCart" />
</div>
</div>
<div style="height:15px;"></div>
</td>
</tr>
</table>
</div>
</div>
}
<div class="button">@Html.ActionLink("Back To Categories","Categories")</div>
<br />
</div>
</div>
@*}*@
@section scripts {
<script src="~/Scripts/jQuery-jScroll.js"></script>
<script src="~/Scripts/jquery.fancybox.js?v=2.1.5"></script>
<script src="~/Scripts/jquery.fancybox-thumbs.js?v=1.0.7"></script>
<script src="~/Scripts/jquery.fancybox-buttons.js?v=1.0.5"></script>
<script type="text/javascript">
//$(function () {
// $('.scroll').jscroll({
// autoTrigger: true
// });
$('.fancybox-thumbs').fancybox({
prevEffect: 'none',
nextEffect: 'none',
closeBtn: true,
arrows: false,
nextClick: false
});
// Document.ready -> link up remove event handler
$(".AddToCart").click(function () {
//first disable the button to prevent double clicks
$(this).prop("disbled", true).prop("value", "Adding...");
$("#sending").css("display", "block");
var td = $(this).closest('td')
//traverse DOM and find relevant element
var price = parseFloat(td.find(".divPrice").prop("id")),
quantity = parseInt(td.find(".quantity").val()),
id = parseInt(td.find(".divId").prop("id"));
$.ajax({
url: "@Url.Action("AddToCartAJAX", "Orders")",
type: "POST",
data: { "id": id, "quantity": quantity, "price": price },
//if successful
success: function (data) {
successfulCall()
},
error: function (data) {
errorCall(data);
}
});
function successfulCall() {
//enable the send button
$(this).prop("disbled", false).prop("value", "Add To Cart");
//hide the sending gif
$("#sending").css("display", "none");
//display the successful message
$("#ItemAdded").text("Your item has been added to your order.");
//clear out all the values
$("input#quantity").val("0");
}
function errorCall(data) {
$(this).prop("disbled", false).prop("value", "Add To Cart");
$("#sending").css("display", "none");
$("#ItemAdded").text(data.message);
}
//alert('Clicked!');
});
//s});
</script>
}
EDIT #2
Here is the code for AddToCartAJAX in OrdersController:
public ActionResult AddToCartAJAX(int id, int quantity, decimal price)
{
var cart = ShoppingCart.GetCart(this.HttpContext);
cart.AddToCart(id, quantity, price);
return RedirectToAction("Index");
}
And AddToCart in ShoppingCrt.cs:
public void AddToCart(int id, int quantity, decimal price)
{
// Get the matching cart and product instances
var order = entities.Orders.FirstOrDefault(
c => c.OrderGUID == ShoppingCartId
&& c.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductId == id);
if (order == null)
{
// Create a new order since one doesn't already exist
order = new Order
{
InvoiceNumber = Guid.NewGuid().ToString(),
OrderDate = DateTime.Now,
OrderGUID = ShoppingCartId,
IsShipped = false
};
entities.Orders.Add(order);
// Save changes
entities.SaveChanges();
//add the OrderItem for the new order
OrderItem oi = new OrderItem()
{
OrderId = order.OrderId,
OrderGUID = ShoppingCartId,
ProductId = id,
ProductQuantity = quantity,
ProductPrice = price
};
entities.OrderItems.Add(oi);
entities.SaveChanges();
}
else
{
// If the item does exist in the cart,
// then add one to the quantity
order.OrderItems.Where(p => p.ProductId == id).FirstOrDefault().ProductQuantity += quantity;
}
}
Hope that helps