Append and Remove Multiple Data Attributes to URL with JQuery - javascript

Having a tuff time figuring this out. I am building a front-end WooCommerce cart component that will add multiple products to the cart by passing the product ID into the URL. The URL structure will ultimately look like this http://cleancolor.staging.wpengine.com/?add-to-cart=2998,3339,2934 where the 2998,3339,2934 are the WooCommerce Product ID's.
Here is a live working version (without the append) http://studiorooster.com/dojo/cleancolor/ - just click on a "5 Pack" or "10 Pack" and select an addon. I have the product id's appended to the Addon name to the right side list and have the attribute named data-itemid
Here is my html block
<div class="col-md-3 clearfix" id="order_summary_box">
<div class="summary-box">
<div class="heading-total">Order Summary : <span class="color-txt" id="order_total"><span>$</span>0</span>
</div>
<div class="summary-basic-pack">
<h5>Whats in Your Bundle</h5>
<ul class="entree-add" id="entree-add">
<li id="no-entrees">No Entrees Added</li>
</ul>
<ul class="pack-add" id="pack-add">
<li id="no-addons">No Addons Selected</li>
</ul>
</div>
<div class="orderbtn-area">
<div class="order-btn-cont"><i class="fa fa-check-circle-o" aria-hidden="true"></i> Subscribe Now !</div>
</div>
</div>
</div>
jQuery
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
}
cart_update();
});
// on click order button submit the form
$('#order_btn_id').on("click", function () {
$('a').attr("href", "http://cleancolor.staging.wpengine.com/?add-to-cart=");
});

Determine whether the window has a push stat
Find all elements that are added to the .pack-add and extract their number
Compile a , delimited string
The following sections that starts and end with //*************
in the snip below should do the trick. Probably you can refactor it into a function.
// add and remove check box items on summary
$('#get-started').delegate('.check-opt', 'click', function () {
let cost = '0';
let itemname = '';
let first = '';
let itemid = ''
if ($(this).is(':checked')) {
cost = $(this).attr('data');
itemid = $(this).attr('data-itemid');
order_additional_options += Number(cost);
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
$("#no-addons").remove();
$(".pack-add").append("<li data-cost='" + cost + "' data-id='item_" + first + cost + "' data-itemid='" + itemid + "'>" + itemname + itemid + "</li>");
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
// **********************END OF NEW CODES
} else { // minus unchecked value
cost = $(this).attr('data');
itemname = $(this).attr('value');
first = itemname.slice(0, itemname.indexOf(" "));
order_additional_options -= Number(cost);
$('[data-id=item_' + first + cost + ']').remove();
// ********************* INSERTED CODES
var all_values=""
$(".pack-add").children().each(function(){
all_values+=$(this).attr('data-itemid')+" "
})
console.log(all_values.trim().replace(" ",","));
var query_string="?add-to-cart="+all_values.trim().replace(/ /g,",");
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + query_string;
window.history.pushState({path:newurl},'',newurl);
}
}
cart_update();
});

Related

onclick not working for two or more links for same function in javascript

I have displayed records from MySQL database. After displaying records added javascript onclick function. It works only for the first record and not works for other records.
In the above image, I clicked the first link which works fine. But if I click second click nothing happens.
<script>
function Confirm(title, msg, $true, $false, $link) {
/*change*/
var $content =
"<div class='dialog-ovelay'>" +
"<div class='dialog'><header>" +
" <h3> " +
title +
" </h3> " +
"<i class='fa fa-close'></i>" +
"</header>" +
"<div class='dialog-msg'>" +
" <p> " +
msg +
" </p> " +
"</div>" +
"<footer>" +
"<div class='controls' style='text-align:right'>" +
" <button class='button button-danger doAction'>" +
$true +
"</button> " +
" <button class='button button-default cancelAction'>" +
$false +
"</button> " +
"</div>" +
"</footer>" +
"</div>" +
"</div>";
$("body").prepend($content);
$(".doAction").click(function() {
$(this)
.parents(".dialog-ovelay")
.fadeOut(500, function() {
var subtotal = document.getElementById("subtotal").innerHTML;
var price = "<?php echo $price ;?>";
var subtotal = +subtotal + +price;
var totalitems = document.getElementById("totalitems").innerHTML;
var totalitems = +totalitems + +1;
document.getElementById("totalitems").innerHTML = totalitems;
document.getElementById("subtotal").innerHTML = subtotal.toFixed(2);
var total = +subtotal + +8 + +4;
document.getElementById("total").innerHTML = total.toFixed(2);
$(this).remove();
});
});
$(".cancelAction, .fa-close").click(function() {
$(this)
.parents(".dialog-ovelay")
.fadeOut(500, function() {
$(this).remove();
});
});
}
$("#linkdup").click(function() {
Confirm(
"Are you sure you want to Duplicate Frame",
"One more frame will be added to Cart",
"Yes",
"No"
); /*change*/
});
</script>
You are working with IDs here. An ID is unique, if you query it, you will get one result (the first).
Example:
// This selects one
const result = document.getElementById('myId').innerHTML;
console.log(result);
// This selects all
const elements = document.querySelectorAll('[id=myId]');
elements.forEach(function(element) {
console.log(element.innerHTML);
// add click event to element here
});
<div id="myId">Test 1</div>
<div id="myId">Test 2</div>
Use classes for this. Using an ID multiple times is invalid, even though you can make it work as shown in example.

Updating then displaying a variable during jQuery .submit function

On page load I am setting:
var qty = 1;
Then, within the page, the user chooses a product & selects a quantity which is captured as the variable clicks.
I wish to then click a button#addToInventory which will update the qty variable & display it in the console. I am attempting this as follows:
$("#addToInventory").submit(function(event){qty = clicks;console.log(" QTY: " + qty );})
This does not work (the console displaying a qty of 1 regardless of the set value, however immediately after clicking the button, if I then manually type console.log(" QTY: " + qty ) I see the correct qty as set in the console.
I have tried to delay the console.log as follows, but this does not work either:
$("#addToInventory").submit(function(event){qty = clicks;setTimeout(function (){console.log( " QTY: " + qty );}, 1000);})
--EDIT--
The above is a simplified sample of the production code which is as follows:
$.ajax(settings).done(function(response) {
var output = "";
for (i in response.Products) {
var productID = response.Products[i].ProductId;
var name = response.Products[i].Name;
var imagePath = response.Products[i].ImagePath;
var EAN = response.Products[i].EANBarcode;
var price = response.Products[i].PriceDescription;
var offer = response.Products[i].OfferPromotion;
var offerValid = response.Products[i].OfferValidity;
var qty = 0;
output += "<div class='uk-width-medium-1-4'> <div class='md-card'> <div class='md-card-head uk-text-center uk-position-relative'> <div class='uk-badge uk-badge-danger uk-position-absolute uk-position-top-left uk-margin-left uk-margin-top'>" + price + "</div><img class='md-card-head-img' src='" + imagePath + "'/> </div><div class='md-card-content'> <h4 class='heading_c uk-margin-bottom'>" + name + "<span class='sub-heading'>SKU: " + EAN + "</span></h4> <p>" + offer + "</p><p><i>" + offerValid + "</i></p><div align='center'><button data-uk-modal=\"{target:'#modal_" + productID + "'}\" class=\"md-btn md-btn-flat md-btn-flat-primary\" >ADD TO INVENTORY</button><div class=\"uk-modal\" id=\"modal_" + productID + "\"> <div class=\"uk-modal-dialog\"> <div class='uk-modal-header'> <h3 class='uk-modal-title md-card-toolbar-heading-text'><i class='md-icon material-icons'></i> QTY To Add</h3> </div><p class='uk-text-left'>How many <i><b>" + name + "</b></i> do you want to add to your home inventory : <br></p><div class='uk-text-center'> <form id='addToInventory_" + productID + "'> </p><br><h2> <table class='uk-table uk-table-popup uk-table-hover-popup'> <tbody> <td class='uk-text-center' type='button' onClick='clicks_" + productID + "--;updateClickCount_" + productID + "();' id='push-'><i class='md-icon material-icons'></i></td><td class='uk-text-center' id='clickCount_" + productID + "'>1</td><td class='uk-text-center' type='button' onClick='clicks_" + productID + "++;updateClickCount_" + productID + "();' id='push+'><i class='md-icon material-icons'></i></td></tbody> </table> </h2> <br></p><button id='addToInventory_" + productID + "-submit' type='submit' class='md-btn md-btn-flat md-btn-flat-primary'>ADD TO INVENTORY</button></form><scr" + "ipt type=\"application/javascript\">var clicks_" + productID + " = 1;var minimum = 1;function updateClickCount_" + productID + "() {if (clicks >= minimum) {document.getElementById('clickCount_" + productID + "').innerHTML = clicks_" + productID + ";} else {clicks_" + productID + " = 1;document.getElementById('clickCount_" + productID + "').innerHTML = clicks_" + productID + ";}} $(\"#addToInventory_" + productID + "\").submit(function(event){qty = 0;console.log('QTY IS: '+qty+' CLICKS Are: '+clicks_"+productID+");qty = clicks_"+productID+";setTimeout(function (){console.log(\""+ name + " QTY: " + qty +"\");}, 1000);}) </scr" + "ipt></div></div></div></div></div></div></div>";
}
$("#allResults").html(output);
$("#searchTerm").html(searchTerm);
});
});
Your qty will always be one because you are creating the variable and assigning it to be 0 inside of the for loop. Every time it runs the for loop a new qty var is created an set to 0 then it is given the 1 value for the iteration variable (i). So the fact that qty is being instantiated in the loop it will never increase.
If you move the qty variable out of the for loop it should work.
var qty = 0;
For (.............) {
// your code here
}

event.target.id.indexOf("foo") not working - Not working in IE

I have a JavaScript function that loops through classes and gets an ID which I have wrapped in a div called 'item'. Once they click on a button it bubbles up through the div which I have wrapped information in and collected the ID. For Example:
output = "<div id='item" + json_output[i].id + "'>" +
"<div class = 'itemBoxes'>"+
"<h3 class ='itemTitle'>" +json_output[i].classname + "</h3>" +
"<div class = 'paddingBottom'></div>" +
"<p class = 'itemDesc'>" + json_output[i].classdescription + '</p>' +
"<div class ='itemInfo'>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-268-credit-card.png'</img> <p class = 'itemDetails'>£" + json_output[i].classprice + "</p></div> "+
"<div class ='bookingItems'> <img src = 'img/glyphicons-46-calendar.png'</img> <p class = 'itemDetails'>" + json_output[i].classdate + "</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-55-clock.png'</img><p class = 'itemDetails'>"+ json_output[i].classstarttime +"</p></div>" +
"<div class ='bookingItems'> <img src = 'img/glyphicons-44-group.png'</img><p class = 'itemDetails'>" + json_output[i].classparticipants + " spaces </p></div>" +
"</div>" +
"<p id ='bookingBox'> <input type='button' class='bookingSubmit' value='Book Now'/> </p>" +
"</div>" +
"</div>";
target.innerHTML += output;
The code I use to find the ID is:
var fetchModifyButton;
//Gets the button that says 'Modify'
fetchModifyButton = _c("bookingSubmit");
//Remove Button.
for (var i = 0, j = fetchModifyButton.length; i < j; i++) {
fetchModifyButton[i].addEventListener("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});
}
This works perfectly in Google Chrome, IE11, and most other browsers.
It doesn't work in IE8,9 or 10.
The error message I get in is:
SCRIPT5007: Unable to get property 'id' of undefinded or null reference
Then it points to the line: while (e.id.indexOf('item') == -1) {
I wondered if anyone had any ideas why?
use event.srcElement for IE
var addEvent = window.addEventListener||window.attachEvent;
fetchModifyButton[i].addEvent("click", function () {
var e, productID, newID;
//Bubbles up and finds the ID of the product they want to modify
e = event.target||event.srcElement;
while (e.id.indexOf('item') == -1) {
e = e.parentNode;
}
productID = e.id;
//Removes everything but the numbers.
newID = productID.replace(/[^0-9.]/g, "");
getClassInfoForBooking(newID, newID);
});

Hiding <p> field in javascript

Here's my code for gathering titles/posts from reddit's api:
$.getJSON("http://www.reddit.com/search.json?q=" + query + "&sort=" + val + "&t=" + time, function (data) {
var i = 0
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
i++
});
});
Basically every post (selftext) is assigned a different paragraph id (post0, post1, post2, etc) for every result that's pulled. I'm also going to create a "hide" button that follows the same id scheme based on my i variable (submit0, submit1, submit2, etc). I want to write a function so that based on which button they click, it will hide the corresponding paragraph. I've tried doing an if statement that's like if("#hide" + i) is clicked, then hide the corresponding paragraph, but obviously that + i doesn't work. How else can I tackle this?
Could you try something like the below?
showhide = $("<a class='hider'>Show/Hide</a>");
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
}
Alternatively:
$.each(data.data.children, function (i, item) {
var title = item.data.title
var url = item.data.url
var id = item.data.id
var subid = item.data.subreddit_id
var selftext = item.data.selftext
var selftextpost = '<p id="post' + i + '">' + selftext + '</p><br>'
var showhide = $("<a class='hider" + i + "'>Show/Hide</a>");
var post = '<div>' + '' + title + '' + '</div>'
results.append(post)
results.append(selftextpost)
results.append(showhide);
$(showhide).click(function() {
$(this).next().toggle();
});
i++
});

Append new <li> and increase its ID number by 1

So I'm trying to append a new <li> and increase its ID number by 1 every time so I end up having something like:
<ul id="bxs">
<li id="item-1">1</li>
<li id="item-2">2</li>
<li id="item-3">3</li>
<li id="item-4">4</li>
<li id="item-5">5</li>
<li id="item-6">6</li>
</ul>
This is what my jQuery looks like:
var itemCount = 1;
$(function() {
$("#NewItem").click(function(e) { // NewItem is my button
e.preventDefault();
itemCount++;
var element = $("<li id="item-" + itemCount>" + itemCount + "</li>");
$("#bxs").append(element);
});
});
What I'm I doing wrong? There must be something wrong on where I add the itemCount in the div. I tried this as well: <li id="item-" + itemCount + "> but doesn't work either.
Can someone guide me please?
Your not concatenating your string properly. You should be using single quotes inside your double quotes. In addition, you can't set itemCount = 1 if you already have existing items. I suggest setting itemCount dynamically. See example below (and fiddle).
$(function() {
$("#NewItem").click(function(e) { // NewItem is my button
e.preventDefault();
var itemCount = ($("[id^='item-']").length + 1);
var element = $("<li id='item-" + itemCount + "'>" + itemCount + "</li>");
$("#bxs").append(element);
});
});
Here's a working fiddle.
try this...
var element = $("<li id='item-" + itemCount +"'>" + itemCount + "</li>");
That is a a weird string, try using single quotes fro your string instead;
var element = $('<li id="item-' + itemCount + '">' + itemCount + '</li>');
Why are you using $( in front of the HTML code?
var element = '<li id="item-' + itemCount+ '">' + itemCount + '</li>';
Think this does the trick
var element = $("<li id="item-" + itemCount>" + itemCount + "</li>");
needs to be
var element = '<li id="item-' + itemCount + '">' + itemCount + '</li>';
I always opt to use the API when possible. It saves issues like this.
var element = $("<li></li>", { id: "item-" + itemCount }).html(itemCount);

Categories