This code is used to remove a cart-item from a partial view.
$(document).on('click', '.RemoveLink', (function (e) {
e.preventDefault();
var recordToDelete = $(this).attr("data-id");
var itemID = $(this).attr("data-itemid");
if (recordToDelete != '') {
$.post("/ShoppingCart/RemoveFromCart", { "id": recordToDelete, "itemID": itemID },
function () {
$('.container-cart').load('#Url.Action("cartDropDown","ShoppingCart")', function () {
$('.cart-dropdown').css('display', 'inline-block');
}
);
});
}
}));
This works well for the first iteration but from the second iteration on-wards, every click of a remove of an item is resulting in deletion of 2 items of a kind. Suppose we had 4 items of pencils and 8 items of pens. Clicking delete pencil button once will result in deletion of 2 pencils and vice versa.
This is probably because of the logic used. Following is the html that is rendered when $('.container-cart').load('#Url.Action("cartDropDown","ShoppingCart")' executes:
#model OnlineStore.ViewModels.ShoppingCartViewModel
<div class="container-cart">
#if (Model.ItemCount == 0)
{
<div>
<span>
There are no items in your cart. Continue shopping.
</span>
</div>
}
else
{
<ul class="cart-dropdown">
<li>
<div class="cart-items cart-caption">
<ul>
#foreach (var i in Model.CartItems)
{
<li id="list-item-#i.item.ItemID">
<div class="container-fluid item-wrap" style="position: relative">
<div class="item-remove">
<a href="#" class="RemoveLink"
data-id="#i.RecordID" data-itemid="#i.item.ItemID">
x
</a>
</div>
<div class="col-md-2 item-img">
<div class="row-cart">
<img alt="" id="cartImg" height="71" width="75" src="#i.item.ImageUrl">
</div>
</div>
<div class="col-md-5 item-info">
<div class="row-cart">
<div class="brand-name">
<a href="#" class="brandName">
#i.item.BrandName
</a>
</div>
<div class="product-name">
<a href="#" class="productName">
#i.item.ItemName
</a>
</div>
<div class="product-qty">
<p class="productQTY" id="item-count-#i.item.ItemID">
#i.Count x #i.item.ItemPrice
</p>
</div>
</div>
</div>
<div class="col-md-5 price-info">
<div class="row-cart" style="margin-top: 10px">
<div class="col-md-6">
<div class="row-mrp">
<span class="cartItemPrice" id="item-total-#i.item.ItemID">
Rs #(#i.Count * #i.item.ItemPrice)
</span>
</div>
</div>
</div>
</div>
</div>
</li>
}
</ul>
</div>
</li>
<li class="clearfix">
<div class="col-md-6">
<div class="row-cart sub-cost" style="background: #fff; margin-left: -10px; margin-right: 0">
<p>
Sub Total :
<span style="float: right">
Rs
<span class="ng-binding"></span>
</span>
</p>
<p>
Delivery Charge :
<span qa="delChargeMB" style="float: right">Free</span>
</p>
</div>
<div class="row-cart cart-chkout-btn">
<button type="button">View Basket & Checkout</button>
</div>
</div>
</li>
</ul>
}
</div>
This html is the partial view that is initially rendered when user clicks a button to view the cart-items. So when user clicks on 'remove an item' button on this partial view, an ajax call is sent to server to remove an item from the cart-items and on success, load the UI again by rendering this partial view once again with new values from the database.
All this is working fine for the first iteration of the deletion of an item from the cart-item list. But when I'm deleting an item again as a second deletion, code is running twice. I'm guessing this is because <div class="container-cart"> is rendered twice on the page as after the first deletion, I can see it on the live DOM inside the browser that <div class="container-cart"> is encolsed inside another <div class="container-cart"> and then the normal elements are rendered in sequence. I'm guessing maybe that's why javaScript is rendered twice or running twice.
Please suggest what you think about it and help me resolve it.
Thanks in advance
After deletion of an item try to use location.reload(); instead of hitting the MVC action method again!
Related
I have the following snippet of code,
<div ng-controller="GraphCtrl" ng-if="errorTracerouteResultsLength!=0">
<h5>Erroneous Traceroute Paths
<small>Sub-heading</small>
</h5>
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">
S: {{val.source.ip}}
D: {{val.destination.ip}}
</a>
</div>
It works fine, loadTraceroutePath belongs to another controller,(lets call it X) but somehow ng-click works and console.log gets printed out with the correct metadata value.
However, in controller X, I have,
$scope.loadIndividualTraceroutePath = function (metadataKey) {
$scope.noOfResults = 1;
}
In the html, I have {{noOfResults}} all over the place. Some of it are able to display 1 while some can't. I have already attached the ng-controller directives and point to controller X, but {{noOfResults}} does not display.
How can I make {{noOfResults}} display in any section of the HTML?
Edit: I have added the HTML.
<div class="row">
<div class="col-lg-9">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bar-chart-o fa-fw"></i> Visualisation
<div class="pull-right">
Layout
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="container" ng-controller="X">
<!--This does not work-->
{{noOfResults}}
</div>
<div>
<div ng-controller="IndividualTraceroutePathGraphCtrl" id="individual_traceroute_path_graph"></div>
</div>
</div>
<!-- /.panel-body -->
</div>
<!-- /.panel -->
</div>
The ng click in the first part of this question is way below.
You have a extra ; at the end, also you are not using the object what you are passing as a parameter to the function, hence Change
From:
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val.metadata);">
To:
<a href="#" ng-repeat="(key, val) in errorTracerouteResults" ng-click="loadTraceroutePath(val)">
Then,
$scope.loadIndividualTraceroutePath = function (metadataKey) {
$scope.noOfResults = 1;
}
EDIT
You don't need to mention so many controllers in the view, have one controller where the function is defined and remove the rest, here, Update like this,
<div class="container" >
<!--This does not work-->
{{noOfResults}}
</div>
<div>
<div id="individual_traceroute_path_graph"></div>
</div>
</div>
html code:
<div ng-controller="reviewsController as revCtrl ">
<div ng-repeat="review in revCtrl.proreviews>
<div ng-init="revCtrl.checklikereview(review)"> LIKE
<div ng-if="review.likestats" ng-href="#" ng-click="revCtrl.removelikereview(review._id)" class="glyphicon glyphicon-star ">
</div>
<div ng-if="!review.likestats" ng-href="#" ng-click="revCtrl.addlikereview(review._id)" class="glyphicon glyphicon-star-empty ">
</div>
<span ng-bind="review.numoflikes"></span>
</div>
<div ng-init="revCtrl.checkdislikereview(review)"> DISLIKE
<div ng-if="review.dislikestats" ng-href="#" ng-click="revCtrl.removedislikereview(review._id)" class="glyphicon glyphicon-star ">
</div>
<div ng-if="!review.dislikestats" ng-href="#" ng-click="revCtrl.adddislikereview(review._id)" class="glyphicon glyphicon-star-empty ">
</div>
<span ng-bind="review.numofdislikes"></span>
</div>
</div>
the problem occurring is that the user is able to do multiple clicks on the div which increases the likes/dislikes by 2 or more
how to disable this?
You can use two different div's one to validate and other to call function
in one div you can use like this
ng-if="review.likestats" ng-href="#"
and inside that div you can put other one to call function
ng-click="revCtrl.removelikereview(review._id)";
try this. I'm not sure if this will work with your code. Give it a try.
<a class="toggle" data-stats="like">Like</a>
<a class="toggle" data-stats="dislike">Like</a>
javascript
var toggle = getElementsByClassName('toggle'),
i;
function func(){
setInterval(function(){
var stat = this.dataset.stats;
if(stat == 'like')
// count + 1
else
// dislike count + 1
}, 3000);
}
for(i = 0; i < toggle.length; i++) toggle[i].addEventListener('click', func);
I made this script, and despite one oddity, it works fine. It's hiding/showing the parent of div element with a class containing specific content. The problem when I press my <a> elements, that act as buttons, they "filter" the divs, but it leaves the first comment <a>? If I change the element do a <div> instead no problem, but with an <a> element it behaves weirdly? Is this just a bug or?
here is a JSFiddle: https://jsfiddle.net/g1puxhs7/2/
HTML:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js">
</script>
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a>Comment</a>
</div>
</div>
<style>
.row {
width: 200px;
margin: 10px;
background: #ccc;
padding: 4px;
}
</style>
SCRIPT:
//--Filter by Status--//
$('.viewBtn').click(function() {
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});
The problem is with your links:
<a class='viewBtn'>Published<a>
<a class='viewBtn'>Completed<a>
<a class='viewBtn'>Created<a>
You have 6 opening a tags, instead of 3 opening and 3 closing tags.
This is why the browser adds closing a tags in your script in a bunch of places, one of them in your first div—and then your whole DOM tree looks different than what you want.
Your markup needed to be cleaned up. Here is your markup cleaned up. Also, i find it best to add href for you anchor tags, and then you can comment them out with #, or you can add javascript:void(0). If you use the # approach, in your JS, you can add e.preventDefault();
HTML Cleaned:
<div>
<a class='viewBtn' href="#">Published</a>
<a class='viewBtn' href="#">Completed</a>
<a class='viewBtn' href="#">Created</a>
</div>
<div class="orders" id="orders">
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff" onclick="Comment">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
<div class="row">
<div class="status">
Completed
</div>
<a class="stuff">Comment</a>
</div>
</div>
JS with preventDefault():
$('.viewBtn').click(function(e) {
e.preventDefault();
var txt = $(this).text();
$('.status:contains("' + txt + '")').parent().toggle();
$(this).toggleClass('down');
});
I have a piece of code:
$("body").on("click", ".reply-button", function(){
alert("test");
});
That is suppose to alert me when I click on an element that is generated on the fly (it is not part of the DOM when this code is executed).
Sometimes it works just as it's suppose to. I click the button and a little alert pops up. However, other times it stop working. Nothing I bind to it will work. If I bind to the container div (also generated on the fly), it does work, but not if I change the handler to incorporate button.
I am asking for what could be the possible reasons for this error? I do not know how to go about debugging this. My first guess was that it was something due to stopImmediatePropagation or stopPropagation but I couldn't find that being used in the same area.
Does anyone have any idea on how I should go about debugging this?
EDIT:
How is the DOM being generated?
I get the HTML from a template that's hidden.
var html = $("#template").html();
Then I append the template to a div container
$("#container").append(html);
EDIT2:
Here is the template being pulled:
<div id="tweets-container" class="feed-wrapper">
</div>
<div id="tweet-template" style="display:none;">
<!-- Tweet 1 -->
<div class="tweet animated" data-scannedTweetId="s_id">
<!-- User -->
<div class="tweet-user">
<!-- User picture -->
<img class="tweet-user-picture" src="s_twt_owner_profile_img_url" />
<!-- User info -->
<div class="tweet-user-info">
<!-- User name -->
<div class="tweet-user-info-name">
s_twt_owner_name (#s_twt_owner_sn)
</div>
<!-- User biography -->
<div class="tweet-user-info-biography">
s_twt_owner_desc
</div>
</div>
</div>
<!-- User statistics (following, followers, and tweets) -->
<span class="tweet-statistics animated">
<div class="following">
<div class="statistic-count">s_twt_owner_num_following</div>
<div class="statistic-label">following</div>
</div>
<div class="followers">
<div class="statistic-count">s_twt_owner_num_follower</div>
<div class="statistic-label">followers</div>
</div>
<div class="tweets">
<div class="statistic-count">s_twt_owner_num_twt</div>
<div class="statistic-label">tweets</div>
</div>
</span>
<!-- Tweet bars/graph -->
<div class="side-information animated">
<div class="bar-wrapper">
<!-- Actual bars -->
<div class="bars">
<div class="bar big-bar bar-green" style="height: tqes_heightpx; background: tqes_color;" data-toggle="tooltip" data-placement="top" title="tq_engage_score"></div>
<div class="bar bar-yellow" style="height: tqrs_heightpx; background: tqrs_color;" data-toggle="tooltip" data-placement="top" title="tq_relevancy_score"></div>
<div class="bar bar-light-green" style="height: sks_heightpx; background: sks_color;" data-toggle="tooltip" data-placement="top" title="s_klout_score"></div>
<div class="bar bar-green" style="height: sls_heightpx; background: sls_color;" data-toggle="tooltip" data-placement="top" title="s_legitimacy_score"></div>
<div class="bar bar-gray" style="height: tqgs_heightpx; background: tqgs_color;" data-toggle="tooltip" data-placement="top" title="tq_geography_score"></div>
</div>
<!-- Labels that correspond with each bar -->
<div class="bar-labels">
<div class="bar-label big-bar-label" data-toggle="tooltip" data-placement="bottom" title="Score">tq_engage_score</div>
<div class="bar-label-icon" style="font-size: 12px; color: #000;" data-toggle="tooltip" data-placement="bottom" title="Relevancy">
<i class="fa fa-bullseye"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Influence">
<i class="fa fa-users"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Legitimacy">
<i class="fa fa-check-circle"></i>
</div>
<div class="bar-label-icon" data-toggle="tooltip" data-placement="bottom" title="Geography">
<i class="fa fa-map-marker"></i>
</div>
</div>
</div>
<!-- Notes below the bars/graph -->
<div class="explanations">
<!-- Note below the bars/graph -->
<div class="explanation">
<div class="explanation-check"><i class="fa fa-first-comment"> </i>
<div class="explanation-text">
comment_one
</div>
</div>
</div>
<!-- Note below the bars/graph -->
<div class="explanation">
<div class="explanation-check"><i class="fa fa-second-comment"> </i>
<div class="explanation-text">
comment_two
</div>
</div>
</div>
</div>
</div>
<!-- Tweet score -->
<div class="score-wrapper">
<div class="score animated">tq_engage_score</div>
</div>
<!-- Tweet content -->
<div class="tweet-content">
s_twt_text
</div>
<!-- Time since tweet was posted -->
<div class="tweet-time-elapsed">
s_twt_time
</div>
<!-- Area below tweet with reply textarea and buttons -->
<div class="tweet-reply-section animated">
<!-- Reply textarea -->
<textarea class="tweet-reply animated">#s_twt_owner_sn </textarea>
<!-- Buttons -->
<div class="buttons animated">
<!-- Small buttons on top of reply button -->
<div class="top-buttons">
<span class="character-count">
</span>
</div>
<!-- Reply button -->
<div class="reply-button">
Reply <i class="fa fa-reply"></i>
</div>
</div>
</div>
</div>
</div>
JavaScript:
/**
* Add a tweet to the feed.
*/
function _addTweetToFeed(tweet, keywords) {
/** Get the tweet template */
var tweetHtml = $('#tweet-template').html();
// add score heights and colors properties to the tweet
tweet = _setScoreBars(tweet);
/** Linkify elements of the tweet */
tweet.s_twt_text = twitterify(tweet.s_twt_text); // the tweet
tweet.s_twt_owner_desc = twitterify(tweet.s_twt_owner_desc);
// fix search terms to be highlighted
tweet.s_twt_text = _highlightSearchTerms(tweet.s_twt_text, keywords); // the tweet
tweet.s_twt_owner_desc = _highlightSearchTerms(tweet.s_twt_owner_desc, keywords);
// change from twitter links to readable links
tweet = _fixTweetLinks(tweet);
/** Make numbers readable */
tweet.s_twt_owner_num_following = abbrNum(tweet.s_twt_owner_num_following, 1);
tweet.s_twt_owner_num_follower = abbrNum(tweet.s_twt_owner_num_follower, 1);
tweet.s_twt_owner_num_twt = abbrNum(tweet.s_twt_owner_num_twt, 1);
/** Loop through the properties of tweet object and populate tweetHtml with them */
for (var prop in tweet) {
if (tweet.hasOwnProperty(prop)) {
tweetHtml = _replaceAll(tweetHtml, prop, tweet[prop]);
}
// add comments
tweetHtml = _addComments(tweet, tweetHtml);
/** If both location and url are not present, remove the comma */
if (!(tweet.s_twt_owner_loc && tweet.s_twt_owner_url)) {
$('#url_comma').html('');
}
}
$('#tweets-container').append(tweetHtml);
}
"Sometimes it works just as it's suppose to" this line alone suggests that you run your code prior to DOM creation. sometimes your browser creates the dom fast enough and the handler is being attached to the body, and sometimes your javascript runs first and it isnt being attached. wrap your code in this:
$(function(){
$("body").on("click", ".reply-button", function(){
alert("test");
});
});
Does anyone have any idea on how I should go about debugging this?
Sometimes it's best to pull out a tiny portion of code, and see if it works in isolation. For example: http://jsfiddle.net/6v7z9fak/
js:
$("body").on("click", ".reply-button", function(){
alert("test");
});
html:
<button type="button" class="reply-button">Reply</button>
As you'll see, it works fine. So you can be confident that the error is not in that bit of code alone. It is either another part of the code, or how the parts are interacting together, or something else. Now slowly add more code, test, and see where it breaks.
I've got six divs that act as buttons. When clicked, one of the spans in a different div (and class) is displayed, and others are hidden.
Buttons:
<div class="menu">
<div class="menubutton">
Menu1
</div>
.
.
.
<div class="menubutton">
Menu6
</div>
</div>
Info shown based on clicked button:
<div class="information">
<span class="information1"> Info1 </span>
...
<span class="information6"> Info6 </span>
</div>
How do I know which one called the function, so I can know which span to make visible?
Provided your markup is this way:
<div class="menu">
<div class="menubutton">
Menu1
</div>
<div class="menubutton">
Menu2
</div>
<div class="menubutton">
Menu3
</div>
<div class="menubutton">
Menu4
</div>
<div class="menubutton">
Menu5
</div>
<div class="menubutton">
Menu6
</div>
</div>
<div class="information">
<span class="information1"> information1 </span>
<span class="information2"> information2 </span>
<span class="information3"> information3 </span>
<span class="information4"> information4 </span>
<span class="information5"> information5 </span>
<span class="information6"> information6 </span>
</div>
You can do this:
$('.menubutton').click(function(){
var index = $('.menubutton').index(this); //get the index of the menubutton clicked
$('.information > span').eq(index).show().siblings().hide(); // show the corresponding information item based onthe clicked one's index and hide others.
});
Demo
with this you can safely remove the class with index like information1, information2 etc instead you can add a common class say content
<div class="information">
<span class="content"> information1 </span>
<span class="content"> information2 </span>
<span class="content"> information3 </span>
<span class="content"> information4 </span>
<span class="content"> information5 </span>
<span class="content"> information6 </span>
</div>
and change it to:
$('.menubutton').click(function(){
var index = $('.menubutton').index(this); //get the index of the menubutton clicked
$('.information > .content').eq(index).show().siblings().hide(); // show the corresponding information item based onthe clicked one's index and hide others.
});
Since you can't have ID's, we can get the index of the clicked menu item, add 1, then find the corresponding information span to show:
$(".menubutton").click(function() {
var menuIndex = $(this).index() + 1;
$(".information" + menuIndex).show();
});
The this keyword inside a function refers to the element that called the function.
Add the #id for each menubutton, so:
<div class="menubutton" id="btn_1"></div>
then:
$(".menubutton").on("click", function() {
// Get the id of button clicked.
var id = $(this).attr("id").split("_")[1];
// Target SPAN with the same id.
$("SPAN.information" + id).show();
});