Add/Remove button Ajax only show one - javascript

I have 2 buttons with this ajax and they both show on the page,how can i make it that only Add to favorites button is shown and when i click it the Remove From Favorites button takes it place ?
function Fav(gameId) {
var url = '#Url.Action("AddToCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId,
},
});
};
function UnFav(gameId) {
var url = '#Url.Action("RemoveFromCollection", "UserCollection")';
$.ajax({
url: url,
type: 'GET',
data: {
gameId: gameId
},
});
};
<button class="btn-link" onclick="Fav(#Model.Id)"><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link " onclick="UnFav(#Model.Id)"><i class="fa fa-heart-broken"></i>Remove From Collection</button>

Try something like this.
DRY (Don't Repeat Yourself)
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection")',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection")'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action="+whichButton+"]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
});
});
.hide { display: none; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>

This is the final result that i was looking for
const urls = {
"AddToCollection": '#Url.Action("AddToCollection","UserCollection",new { gameId = Model.Id })',
"RemoveFromCollection": '#Url.Action("RemoveFromCollection","UserCollection",new { gameId = Model.Id })'
}
function Fav(gameId, action) {
$.ajax({
url: urls[action],
type: 'GET',
data: {
gameId: gameId,
},
});
};
$(function() {
const whichButton = "AddToCollection"; // set which one to show here using whatever method
$(".btn-link[data-action=" + whichButton + "]").show();
$(".btn-link").on("click", function() {
Fav(this.dataset.id, this.dataset.action)
$(this).siblings().hide();
$(this).siblings().show();
$(".btn-link[data-action=" + whichButton + "]").hide();
});
});
.hide {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="favDiv">
<button class="btn-link hide" data-action="AddToCollection" data-id=""><i class="fa fa-heart"></i>Add To Collection</button>
<button class="btn-link hide" data-action="RemoveFromCollection" data-id=""><i class="fa fa-heart-broken"></i>Remove From Collection</button>
</div>

Related

How to prevent ajax send multiple request when change input data

Im using ajax to send a parameter from input field in Modal to Controller,
But when i change the value and close the modal, ajax remember it and when i call it, Ajax request multiple times, with old values and the new of the input.
<!--Add post to seri -->
<div class="modal fade" id="addModal">
<div class="modal-dialog">
<div class="modal-content">
<!-- Modal Header -->
<div class="modal-header">
<h4 class="modal-title">Add post to serie</h4>
<button type="button" class="close cleardt" data-dismiss="modal">×</button>
</div>
<!-- Modal body -->
<div class="modal-body">
<div class="row">
<div class="col-9">
<input type="number" required id="IDPost" placeholder="Nhập id bài viết" class="form-control" />
</div>
<div class="col-3">
<button class="btn btn-info" id="btnCheck">Check</button>
</div>
</div>
<div class="form-group">
<label for="message-text" class="col-form-label">Bài viết gốc:</label>
<p id="postName" class="text-primary bold">ID không hợp lệ</p>
</div>
</div>
<!-- Modal footer -->
<div class="modal-footer">
<button type="button" id="addPostBtn" disabled class="btn btn-success">Thêm</button>
<button type="button" class="btn btn-secondary cleardt" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
My ajax syntax:
var serieid = '#Model.SerieID';
$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');
$('#addPostBtn').click(function () {
var idpost = $('#IDPost').val();
amodal.modal('hide');
$.ajax({
type: "POST",
url: '/Admin/AddToSerie',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: idpost, seriid: serieid }),
dataType: "json",
success: function (recData) {
var notify = $.notify('<strong>Successfully
</strong><br/>' + recData.Message + '<br />', {
type: 'pastel-info',
allow_dismiss: false,
timer: 1000,
});
if (recData.reload != false) {
setTimeout(function () {
window.location.reload();
}, 1500);
}
},
error: function () {
var notify = $.notify('<strong>Error</strong><br/>Không thêm được<br />', {
type: 'pastel-warning',
allow_dismiss: false,
});
}
});
});
});
Im finding a way to clear the value queue of input field but it doesnt work
$('#addPostBtn').click add a EventListener to the element.
It is called every time when #addBtn is clicked, so multiple event listeners are attached to addPostBtn. That's why your ajax was called multiple times.
You can fix it by using on and off of jQuery.
...
amodal.modal('show');
$('#addPostBtn').off('click');
$('#addPostBtn').on('click', function () { ... });
Or it can be fixed by moving $('#addPostBtn').click out of $('#addBtn').click function.
$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');
});
$('#addPostBtn').click(function () { ... });
Try appending a unique bit of text to ajax url every time, eg
var ts = (new Date()).getMilliseconds();
$.ajax({
type: "POST",
url: '/Admin/AddToSerie?ts=' + ts,
contentType: "application/json; charset=utf-8",
......
Change the getMilliseconds to provide a genuinely unique value, say by concatenating all the other portions of the date.
v**separate modal click and ajax click event**ar serieid = '#Model.SerieID';$('#addBtn').click(function () {
var amodal = $('#addModal');
$('#IDPost').val(null);
amodal.modal('show');});$('#addPostBtn').click(function () {
var idpost = $('#IDPost').val();
amodal.modal('hide');
$.ajax({ type: "POST",
url: '/Admin/AddToSerie',
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ id: idpost, seriid: serieid }),
dataType: "json",
success: function (recData) {
var notify = $.notify('<strong>Successfully</strong><br/>' + recData.Message + '<br />', {
type: 'pastel-info',
allow_dismiss: false,
timer: 1000,
});
if (recData.reload != false) {
setTimeout(function () {
window.location.reload();
}, 1500);
}
}
});});

Hide AJAX Cart item numers if no item in cart

I'm struggling with some javascript to figure out the proper way to make it work.
I have a button showing the number of items in the cart. By default is zero. As items added the cart the number is increasing. But at the beginning, I don't want to show "0" in the cart.
HTML:
<p id="cart_button" onclick="show_cart();">
<input type="button" id="total_items" value="0">
</p>
<div id="mycart"></div>
<div id="item_div">
<div class="items" id="item1">
<input type="button" value="Add To CART" onclick="cart('item1')">
<p>Simple Navy Blue T-Shirt</p>
<input type="hidden" id="item1_name" value="ITEM-ID1">
</div>
<div class="items" id="item2">
<input type="button" value="Add To CART" onclick="cart('item2')">
<p>Trendy T-Shirt With Back Design</p>
<input type="hidden" id="item2_name" value="ITEM-ID2">
</div>
</div>
JAVASCRIPT:
$(document).ready(function() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
});
function cart(id) {
var name = document.getElementById(id + "_name").value;
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
item_name: name
},
success: function(response) {
document.getElementById("total_items").value = response;
}
});
}
function show_cart() {
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
showcart: "cart"
},
success: function(response) {
document.getElementById("mycart").innerHTML = response;
$("#mycart").slideToggle();
}
});
}
I basically want the button with 0 to be hidden until it gets a value. if it goes back to zero I want it to be hidden again.
Thank you for the help!
You can add 'change' event listener to this button:
let totalItems = $('#total_items');
totalItems.change(function () {
if (totalItems.val() == 0) {
totalItems.hide();
}
else totalItems.show();
});
Also you should trigger this event in your success method of ajax:
success: function(response) {
document.getElementById("total_items").value = response;
totalItems.change();
}
And finally hide this button at start:
<input type="button" id="total_items" value="0" style="display: none">
Check this working in fiddle:
https://jsfiddle.net/xpvt214o/771844/
You can show/hide when update cart:
// Add this function
function update_cart(value) {
document.getElementById("total_items").value = response;
if (value > 0) {
// Show the cart
document.getElementById("total_items").style.display = "block";
} else {
// Hide the cart
document.getElementById("total_items").style.display = "none";
}
}
Then, you need to change your code, when update cart:
$.ajax({
type: 'post',
url: 'store_items.php',
data: {
total_cart_items: "totalitems"
},
success: function(response) {
update_cart(response);
}
});

How to pass data from a component to an Instance in Vue

I am trying to get data from a component and pass it to a variable in my root Vue instance.
My Vue Instance:
new Vue({
el: '#root',
data: {
searchResultObject: ''
},
methods: {
//....
}
});
My Global Component:
Vue.component('user-container-component', {
props: {
prop: null
},
template: '#user-container-template',
data: function () {
return {
searchResultObject: ''
}
},
methods: {
dbSearch_method: function () {
var self = this;
$.ajax({
url: 'Home/LocalSearch',
type: 'GET',
success: function (response) {
self.searchResultObject = response;
},
error: function () {
alert('error');
}
});
}
}
})
Pressing a button in my UI triggers the dbSearch_method, that part works. I am wondering how I get the data to the searchResultObject in my instance, not the component?
HTML:
<button class="btn btn-link bold" v-on:click="dbSearch_method">{{item}}</button></li>
EDIT:
HTML:
<div id="root">
//...
<div id="collapse2" class="panel-collapse collapse">
<ul class="list-group">
<root-component v-for="item in customerObject"
v-bind:prop="item"
v-bind:key="item.id">
</root-component>
</ul>
</div>
</div>
//...
<script type="text/x-template" id="root-template">
<li class="list-group-item">
<div class="bold">
<button v-if="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-down" style="color: black"></span></button>
<button v-else="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-right" style="color: black"></span></button>
<button class="btn btn-link bold">{{prop.name}}</button>
</div>
<ul class="no-bullets" v-show="open">
<park-container-component v-bind:prop="prop.parks"/>
<admin-container-component v-bind:prop="prop.admins" />
<user-container-component v-on:search-results-fetched="addSearchResults($event)" v-bind:prop="prop.admins" />
</ul>
</li>
</script>
<script type="text/x-template" id="user-container-template">
<li class="list-group-item">
<div class="bold">
<button v-if="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-down" style="color: black"></span></button>
<button v-else="open" v-on:click="toggle" class="btn btn-link"><span class="glyphicon glyphicon-chevron-right" style="color: black"></span></button>Users
<button class="btn btn-primary btn-xs pull-right" data-toggle="modal" data-target="#inviteAdminModal">Add</button>
</div>
<ul class="no-bullets" v-show="open" v-for="item in prop">
<li><button class="btn btn-link bold" v-on:click="dbSearch_method">{{item}}</button></li>
</ul>
</li>
</script>
Script:
new Vue({
el: '#root',
data: {
//...
searchResultObject: ''
},
methods: {
//...
addSearchResults: function(data) {
alert('adding');
this.searchResultObject = data;
}
}
});
Vue.component('user-container-component', {
props: {
prop: null
},
template: '#user-container-template',
data: function () {
return {
open: false
}
},
methods: {
toggle: function () {
this.open = !this.open;
},
dbSearch_method: function () {
var self = this;
$.ajax({
url: 'Home/LocalSearch',
type: 'GET',
success: function (response) {
self.$emit('search-results-fetched', response);
},
error: function () {
alert('error');
}
});
}
}
})
As you said the component user-container-component is inside element with id #root, assming your html to be like this:
<div id="root">
<user-container-component></user-container-component>
</div>
in your user-container-component emit an event in the succss callback of your dbSearch_method ajax request like this:
Vue.component('user-container-component', {
props: {
prop: null
},
template: '#user-container-template',
data: function () {
return {
searchResultObject: ''
}
},
methods: {
dbSearch_method: function () {
var self = this;
$.ajax({
url: 'Home/LocalSearch',
type: 'GET',
success: function (response) {
this.$emit('search-results-fetched', response);
},
error: function () {
alert('error');
}
});
}
}
})
in your html setup an event listener on the user-container-component like this:
<div id="root">
<user-container-component #search-results-fetched="addSearchResults($event)"></user-container-component>
</div>
in your root instance add addSearchResults method:
new Vue({
el: '#root',
data: {
searchResultObject: ''
},
methods: {
addSearchResults(data){
this.searchResultObject = data;
}
}
});
You can emit the value as an event for parent to listen to
$.ajax({
url: 'Home/LocalSearch',
type: 'GET',
success: function (response) {
self.searchResultObject = response;
this.$emit('onSearchResult', response)
},
error: function () {
alert('error');
}
});
then in your parent you can fetch it by setup a listener
<user-container-component v-on:onSearchResult="parentListener"/>
For a big project, you can use vuex to manage the data.
Or you can just use eventbus to solve the same level component data transmission.here
For your situation, I think it should use $emit.
dbSearch_method: function () {
var self = this;
$.ajax({
url: 'Home/LocalSearch',
type: 'GET',
success: function (response) {
self.searchResultObject = response;
this.$emit('customEvent', response);
},
error: function () {
alert('error');
}
});
}
and in your root vue instance,you can use $on to listen the event fire.here

How to display CRUD views in a jquery dialog model form, or in a bootstrap popup

<script src="jquery-js">
$("._detailsInfo").click( function () {
var Id = $(this).attr('Id');
$.ajax({
"url": "/Test/Details/"+Id,
"type": "GET",
"dataType": "html",
success: function (response) {
$('#myModal').modal(options);
$('#myModal').modal('show');
},
failure: function (response) {
alert(response.responseText);
}
});
});
</script>
#model BOL3.tbl_Appoiment_Diary
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-header">
<button type="button" class="close" data-dissmiss="modal" aria-hidden="true">x</button>
<h4 class="modal-title" id="myModalLabel">Details</h4>
<hr />
<dl class="dl-horizontal">
<dt>
#Html.DisplayNameFor(model => model.Title)
</dt>
<dd>
#Html.DisplayFor(model => model.Title)
</dd>
</dl>
</div>
<p>
#Html.ActionLink("Edit", "Edit", new { id = Model.ID }) |
#Html.ActionLink("Back to List", "Index")
</p>
</div>
</div>
<td>
#*#Html.ActionLink("Details", "Details", new { id = item.ID }) |*#
<button class="btn btn-info btn btn-xs _detailsInfo" id=" '+ item.ID +' ">Details</button> |
#Html.Partial("_Details", new BOL3.tbl_Appoiment_Diary())
#*#Html.ActionLink("Details", "_Details", new { #class = "_detailsInfo", id = "'+item.ID+'" }) |*#
</td>
Can anyone help me with this. Please keep in mind that I'm quite new working with Javascript and Jquery so any help is greatly appreciated. I tryied different methods from multiple websites but nothing worked. Here are some of the websites that I tryed:
jquery-dialog-with-aspnet-mvc , jquery-dialog, and many others, but nothing seems to work.
Here is what i tryed until now:
public ActionResult Details(int Id)
{
BOL3.tbl_Appoiment_Diary appd = new BOL3.tbl_Appoiment_Diary();
appd = db.tbl_Appoiment_Diary.Find(Id);
return PartialView("_Details", appd);
}
this is the controller part.
<script src="jquery-js">
//$(function () {
// $("#dialog").dialog({
// autoOpen: false,
// modal: true,
// title: "Details"
// });
// $("#AppoimentDiary .details").click(function () {
// var ID = $(this).closest("tr").find("td").eq(0).html();
// $.ajax({
// type: "POST",
// url: "/Test/Details/",
// data: '{ID: "' + ID + '"}',
// contentType: "application/json; charset=utf-8",
// dataType: "html",
// success: function (response) {
// $('#dialog').html(response);
// $('#dialog').dialog('open');
// },
// failure: function (response) {
// alert(response.responseText);
// },
// error: function (response) {
// alert(response.responseText);
// }
// });
// });
//});
//$(document).ready(function () {
// $("#btnCreate").click(function () {
// InitializeDialog($("#testdialog"));
// $("#testdialog").dialog("open");
// });
// function InitializeDialog($element) {
// $.dialog({
// autoOpen: false,
// width: 400,
// resizable: true,
// draggable: true,
// title: "Appointments",
// model: true,
// show: 'slide',
// closeText: 'x',
// dialogClass: 'alert',
// closeOnEscape: true,
// open: function (event, ui) {
// $element.load('/Test/Add');
// },
// close: function () {
// $(this).dialog('close');
// }
// });
// }
//});
//$.ajaxSetup({ cache: false });
//$(document).ready(function () {
// $(".openPopup").live("click", function (e) {
// e.preventDefault();
// $("<div></div><p>")
// .addClass("dialog")
// .attr("id", $(this)
// .attr("data-dialog-id"))
// .appendTo("body")
// .dialog({
// title: $(this).attr("data-dialog-title"),
// close: function () { $(this).remove(); },
// modal: true,
// height: 250,
// width: 900,
// left: 0
// })
// .load(this.href);
// });
// $(".close").live("click", function (e) {
// e.preventDefault();
// $(this).closest(".dialog").dialog("close");
// });
//});
#*var url = '#Url.Action("Details", "Test")';
$('selector').load(url, { id: 1 });*#
</script>
#Html.ActionLink("Det", "Details", new { id = item.ID, #class = "data-toggle = 'modal' data-target = '#myModal' " }) |
<div id="dialog" style="display: none">
</div>
</div>
#*<div id='myModal' class='modal'>
<div class="modal-dialog">
<div class="modal-content">
<div id="myModalContent"></div>
</div>
</div>
</div>
<script src="jquery-js">
var TeamDetailPostBackURL = '/Test/Details';
$(function () {
$(".anchorDetail").click(function () {
debugger;
var $buttonClicked = $(this);
var id = $buttonClicked.attr('data-id');
var options = { "backdrop": "static", keyboard: true };
$.ajax({
type: "GET",
url: TeamDetailPostBackURL,
contentType: "application/json; charset=utf-8",
data: { "Id": id },
datatype: "json",
success: function (data) {
debugger;
$('#myModalContent').html(data);
$('#myModal').modal(options);
$('#myModal').modal('show');
},
error: function () {
alert("Loading the data is not possible!");
}
});
});
$("#closbtn").click(function () {
$('#myModal').modal('hide');
});
});
</script>*#
#*<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header" style="background-color:aqua">
<h4 class="modal-title">Ada New</h4>
</div>
<div class="modal-body">
#Url.Action("/Test/Details")
</div>
<div class="modal-footer" style="background-color:aqua">
<button type="button" class="btn btn-danger" data-dissmiss="modal">Close</button>
<button type="button" data-dismiss="modal" class="btn btn-success">Save</button>
</div>
</div>
</div>
</div>*#
Any help on this topic is greatly appreciated.
Edit:
This is the index button, the script is from your answer:
in the same index view, and here is the partial view:
See, there is no need to call again details method from your modal body.
Create a modal inside partial view, and keep all your partial view HTML inside the modal body. And in top of your partial view, add your modal reference, like bellow,
#model Your_Project_Name.ModalFolderName.tbl_Appoiment_Diary
<div class="modal fade" id="myModal" role="dialog" tabindex="-1">
<div class="modal-dialog">
<div class="modal-header">Details Info</div>
<div class="modal-body">
/*Here keep your all HTML to display details data*/
</div>
</div>
</div>
Change or update the above HTML accordingly. And change the reference name with your project name and class name.
Create your Details button in your main view, like this,
<button class="btn btn-info _detailsInfo" id="'+item.ID+'"></Details>
While click this button call a jquery click function like bellow,
$("._detailsInfo").click(function ()
{
var Id = $(this).attr('Id');
$.ajax({
"url": "/Test/Details/"+Id,
"type": "Get",
"dataType": "html",
success: function (response) {
$('#myModal').modal(options);
$('#myModal').modal('show');
},
failure: function (response) {
alert(response.responseText);
}
});
});
Suppose your partial view name is _Details.cshtml. Then just render it inside your main view like this,(basically keep this bellow code before the close tag of body of your main view)
#Html.Partial("_Details", new tbl_Appoiment_Diary())
That's it! Hope it helps you.

How to remove data from view run-time?

I am developing MVC application and using razor syntax.
In this application I am giving comment facility.
I have added a partial view, which loads the comment/Records from DB.
In below image, we can see the comment box which is called run-time for employee index view.
problem is, when user delete comment, its get deleted from DB but how to remove it from the screen without redirect to any page ?
I wan to remove that deleted comment div tag smoothly...
Please see the image...
my code is...
#model IEnumerable<CRMEntities.Comment>
#{
<div class="ParentBlock">
#foreach (var item in Model)
{
<div class="OwnerClass" id="OwnerName" data-comment-id="#item.Id">
<span class="EmpName"> #Html.ActionLink(item.Owner.FullName, "Details", "EMployee", new { id = item.OwnerId }, new { #style = "color:#1A6690;" })</span>
#Html.DisplayFor(ModelItem => item.CommentDateTime)
<span class="EmpName"><button type="button" class="deleteComment">Delete</button></span>
<p class="CommentP">
#Html.DisplayFor(ModelItem => item.CommentText)
</p>
<br />
<a class="Delete222" style="cursor:move;display:none;">DeleteNew</a>
<br />
</div>
}
<p class="p12">
</p>
</div>
<p id="ClassPara" class="ShowComments" onclick="chkToggle()">Show All Comments</p>
}
#Html.TextArea("Comment", "", 5, 80, "asdsd")
<input type="button" value="Add Comment" id="AddCommentButton"/>
<input type="button" value="Clear" onclick="clearText()"/>
<br />
</body>
</html>
<script src="../../Scripts/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$(".deleteComment").click(function () {
alert("asd");
var commentBlock = $(this).parent('.OwnerClass');
commentBlock.hide('slow')
});
});
$(document).ready(function () {
$('.OwnerClass').hover(function () {
$('.Delete222', this).show();
}, function () {
$('.Delete222').hide();
});
});
</script>
Instead of generating action link, place there button or . Bind JavaScript function to click event on this button, in this function make ajax call to action that deletes comment from db and use Jquery to hide proper div.
<span class="EmpName"><button type="button" class="deleteComment">Delete</button></span>
JavaScript:
$('.deleteComment').click(function ()
{
var commentBlock = $(this).parent('.ParentBlock');
$.ajax({
type: 'post',
url: '/Comment/DeleteComment',
dataType: 'json',
data:
{
commentId: getCommentId(commentBlock )
},
success: function (data) {
commentBlock.hide('slow')
}
});
});
UPDATE:
Update due to question update and comments below this answer:
$(document).ready(function () {
$(".deleteComment").click(function () {
var commentBlock = $(this).parent('.OwnerClass');
$.ajax({
type: 'post',
url: '/Comment/DeleteComment',
dataType: 'json',
data:
{
commentId: commentBlock.attr('data-comment-id')
},
success: function (data) {
commentBlock.hide('slow')
}
});
});
});

Categories