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);
}
});
Related
I am able to fetch all my data from database successfully but only the last item in the array displays. What am I doing wrong?
HTML
#foreach($groups as $group)
<button type ="button" value="{!! $group->id !!}" id="btn" name="btn">{!!$group->name!!}</button>
<div class="panel">
<label for="myvalue"><input type="checkbox" id="myvalue" /> <span>Label text x</span></label>
</div>
#endforeach
JavaScript
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data: {
id: $(this).val(),
access_token: $("#access_token").val()
},
success: function (result) {
$.each(result, function (i, fb) {
$("label[for='myvalue']").text(fb.name);
});
}
);
This way you are replacing the label text, not creating labels. What you are looking for would be something like:
<div class="panel" id="labels_cotainer">
<label for="myvalue">
<input type="checkbox" id="myvalue" />
<span>Label text x</span></label>
</div>
$.ajax({
type: "GET",
url: "/dashboard/ajax=?id=" +id,
data:{
id: $(this).val(),
access_token: $("#access_token").val()
},
success:function(result) {
$.each(result, function (i, fb) {
$("#labels_cotainer").append('<label>'+fb.name+'</label>');
}
}
});
This code will append every label to your panel
You have to dynamically create new labels and add fb.name to it otherwise you will replace all values until the last value
success:function(result) {
$.each(result, function (i, fb) {
$("#outerDiv").append('<label>'+fb.name+'</label>');
});
}
I have this html markup:
<!-- ko foreach: Orders -->
<div class="row">
<div>
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', optionsText: 'TeacherName', optionsCaption: 'Choose Teacher', event: { change: $root.teacherChanged }">
</select>
</div>
<div>
<a href='#' data-bind="click: $root.RequestImage" class="green-btn blue pull-right">
<span class="glyphicon glyphicon-cloud-download"></span> Download
</a>
</div>
</div>
<!-- /ko -->
There will be n number of items in the foreach loop, that will not be known in the moment of development.
What I want to do is when the $root.RequestImage is clicked, the code needs to check if there is selection made in the respected dropdown for that row, if the selection is made then proceed further, otherwise display alert box with 'error' message.
So in the RequestImage that action should happen, this is the RequestImage function currently:
self.RequestImage = function () {
};
How can I achieve this?
Update
OrdersVM:
var self = this;
self.Orders = ko.observableArray([]);
$.ajax({
type: "POST", url: "/webservices/InfoWS.asmx/GetOrders",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
if (data.d != null) {
var orderIds = [];
ko.utils.arrayForEach(data.d, function (item) {
item._teacherOrders = ko.observable();
$.ajax({
type: "POST",
url: "/webservices/InfoWS.asmx/GetTeachersForMyAccount",
contentType: "application/json; charset=utf-8",
data: "{'orderId': " + JSON.stringify(item.OrderId) + "}",
dataType: "json",
success: function (data) {
if (data) {
return item._teacherOrders(data.d);
}
},
error: function (n) {
alert('Error retrieving teachers for orders, please try again.');
}
});
item.TeacherNames = ko.computed(function () {
return item._teacherOrders();
});
self.Orders.push(item);
orderIds.push(item.OrderId);
});
}
},
error: function (data) {
var response = JSON.parse(data.responseText);
console.log("error retrieving orders:" + response.Message);
}
});
I would do it this way:
add an observable selectedTeacher to every order object
add value: selectedTeacher to your selects:
<select class="form-control" data-bind="attr: { id: 'prefix_' + $index() }, options: TeacherNames, optionsValue: 'TeacherId', ..., value: selectedTeacher"></select>
check that observable in your RequestImage event
if ( !data.selectedTeacher() ) {
alert('Error: select teacher')
} else {
alert('Success')
}
A working demo - Fiddle
I am working on single page application, I have been navigating between divs, its simple but i wanted to do it with ajax....
I wanted to do something like When "success" function called then it should send/scroll user view to another div..... I already tried the
.animate but failed....
Any kind of help or reference will be appreciated
<div id="SecondInfo"></div>
<script>
$("#btnSubmit").click(function () {
var FirstName = $('#FirstName').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
data: { "FirstName": FirstName},
success: function (data) {
console.log(data);
$("#SecondInfo").animate({ scrollTop: "0px" });
},
error: console.log("it did not work"),
});
});
</script>
use scrollTop() inside animate() and set the offset from element what you want to focused, here part of code .
$('html,body').animate({scrollTop: $('#second').offset().top}, 200, function() {
//next code
});
Demo JsFIddle
Scroll animate
Try .focus()
<script>
$("#btnSubmit").click(function () {
var FirstName = $('#FirstName').val();
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
data: { "FirstName": FirstName},
success: function (data) {
console.log(data);
$("#SecondInfo").focus();
},
error: console.log("it did not work"),
});
});
</script>
Ok let me assume you have 4 divs and each with single input element as below and the first one will have the active class and remaining will be hidden:
<div id="parentStep">
<div id="div1" class="steps active">
<input type="text" id="firstName"/>
</div>
<div id="div2" class="steps">
<input type="text" id="lastName"/>
</div>
<div id="div3" class="steps">
<input type="text" id="contacNum"/>
</div>
<div id="div4" class="steps">
<input type="text" id="addressDetail"/>
</div>
</div>
Now in your ajax on success just try to find the div with active class and hide it and show div which is next to it as below:
$("#btnSubmit").click(function () {
var activeDiv=$("#parentStep").find('.steps .active');//get the active div
var dataToSend=activeDiv.find('input').val();//get the input value of active div
$.ajax({
type: "POST",
url: '#Url.Action("Submit", "Home")',
dataType: "JSon",
data: { "Data": dataToSend},
success: function (data) {
activeDiv.fadeOut("slow").removeClass('active');//remove active from current step
activeDiv.next().fadeIn('fast').addClass('active');//get the next div visible and add active class
},
error: function(data){
console.log("it did not work"),
}
});
});
I have an email submitting form and when a user submits, I would like to show a confirmation text below the input. After 5 seconds the confirmation text has to fade-out again.
this is my code
<div class="input-group newsletter-group">
<input type="text" class="form-control" id="email-to-submit">
<div id="submit-email" class="input-group-addon">go!</div>
</div>
<div id="email-submit-form">THANKS!</div>
<div id="invalid-email-warning" style="color: red; display: none;">Not an email address</div>
$(function() {
setTimeout(function() { $("#email-submit-form").fadeOut(1500); }, 5000)
$('#submit-email').click(function() {
var emailAddress = $('#email-to-submit').val();
if (validateEmail(emailAddress)){
$('#email-to-submit').val('');
$('#email-submit-form');
$.ajax({
type: "POST",
url: '/submitEmailAddress',
dataType: 'json',
data: JSON.stringify({'email': emailAddress})
});
} else {
$('#invalid-email-warning').show();
}
$('#email-submit-form').show();
setTimeout(function() { $("#email-submit-form").fadeOut(1500); }, 5000)
})
});
You can use jQuery delay()
$('#email-submit-form').fadeIn().delay(5000).fadeOut();
Try this..
$('#email-submit-form').fadeIn('slow', function () {
$(this).delay(5000).fadeOut('slow');
});
Write your timeout logic inside the if(){ condition or ajax success
$.ajax({
type: "POST",
url: '/submitEmailAddress',
dataType: 'json',
data: JSON.stringify({
'email': emailAddress
}),
success: function (response) {
$('#email-submit-form').show();
setTimeout(function () {
$("#email-submit-form").fadeOut(1500);
}, 5000)
}
});
Also,
if (validateEmail(emailAddress)){
$('#email-to-submit').val('');
$('#email-submit-form'); //this line
The third line does nothing, remove it.
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')
}
});
});
});