Checkbox filter array values not joining in url - javascript

I am trying to create a set of filters using checkboxes. When a box is checked, the value is added to the url and the page content filters accordingly.
As it stands, the filters and script is working, but instead of multiple values being joined in the url and content being displayed, the url is being overridden and only using one value from the checkbox array. For example, if WordPress and XL selected, only WordPress will show in the url. I have had a version of this script working but for select options with no issue, but checkboxes are proving an issue and i'm not sure what i've missed..
Can anyone point me in the right direction? : )
Shopify.queryParams = {};
if (location.search.length) {
for (var aKeyValue, i = 0, aCouples = location.search.substr(1).split('&'); i < aCouples.length; i++) {
aKeyValue = aCouples[i].split('=');
if (aKeyValue.length > 1) {
Shopify.queryParams[decodeURIComponent(aKeyValue[0])] = decodeURIComponent(aKeyValue[1]);
}
}
}
jQuery('.coll-picker').change(function() {
if (jQuery(this).val()) {
location.href = '/collections/' + jQuery(this).val();
}
else {
location.href = '/collections/all';
}
});
/* Specify the input */
var collFilters = jQuery('.coll-filter');
collFilters.change(function() {
delete Shopify.queryParams.page;
/* declare an array */
var newTags = [];
// console.log(newTags);
/* This works - if (this) is checked, push value from array : only working for one value though */
collFilters.each(function() {
//if (jQuery(this).val()) { // this works for select options
if (jQuery(this).is(':checked')) {
newTags.push(jQuery(this).val());
// var id = $(this).attr("id"); alert("Checked: " + id);
}
});
{% if collection.handle %}
var newURL = '/collections/{{ collection.handle }}';
if (newTags.length) {
newURL += '/' + newTags.join('+');
}
var search = jQuery.param(Shopify.queryParams);
if (search.length) {
newURL += '?' + search;
}
location.href = newURL;
{% else %}
if (newTags.length) {
Shopify.queryParams.constraint = newTags.join('+');
}
else {
delete Shopify.queryParams.constraint;
}
location.search = jQuery.param(Shopify.queryParams);
{% endif %}
});
<form class="lmwd-filter" method="post">
<ul class="clearfix filter-category">
<li>
<p>Category</p>
{% assign tags = 'Ecommerce, Woocommerce, WordPress, Magento 2' | split: ',' %}
{% for t in tags %}
{% assign tag = t | strip %}
<label for="{{ tag }}">
<input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
{{ tag }}
</label>
{% endfor %}
</li>
<li><br /></li>
<li>
<p>Size</p>
{% assign tags = 'XS, S, M, L, XL' | split: ',' %}
{% for t in tags %}
{% assign tag = t | strip %}
<label for="{{ tag }}">
<input type="checkbox" id="{{ tag | handle }}" class="chk coll-filter" name="{{ tag | handle }}" value="{{ tag | handle }}" />
{{ tag }}
</label>
{% endfor %}
</li>
</ul>
</form>

Related

Shopify variant price change using setCallBack not working

I am trying to update the product price when a variant is selected. So far i have the below; but just cant get it to work.
I have added this script to the theme.liquid
{{ 'option_selection.js' | shopify_asset_url | script_tag }}
I have the price in the product-template.liquid
<div class="product-price"><span id="price-field">{{ product.price | money }}</span></div>
<select
v-model="form.id"
name="id" id="variant-id"
class="minimal mt-2 mb-2 {% if hide_default_title %}hidden{% endif %}">
{% for variant in product.variants %}
{% if variant.available %}
<option
{% if variant == current_variant %}selected="selected"{% endif %}
{% unless variant.available %}disabled="disabled"{% endunless %}
data-inventory-quantity="{{ variant.inventory_quantity }}"
data-price="{{ variant.price | money | strip_html }}"
value="{{ variant.id }}"
class="js-variant-radio">{{ variant.title }}
</option>
{% endif %}
{% endfor %}
</select>
And the callback function here
<script>
// <![CDATA[
var selectCallback = function(variant, selector) {
if (variant) {
if (variant.available) {
// Selected a valid variant that is available.
$('#add').removeClass('disabled').removeAttr('disabled').val('Add to Cart').fadeTo(200,1);
} else {
// Variant is sold out.
$('#add').val('Sold Out').addClass('disabled').attr('disabled', 'disabled').fadeTo(200,0.5);
}
// Whether the variant is in stock or not, we can update the price and compare at price.
if ( variant.compare_at_price > variant.price ) {
$('#price-field').html('<span class="product-price on-sale">'+ Shopify.formatMoney(variant.price, "") +'</span>'+' <s class="product-compare-price">'+Shopify.formatMoney(variant.compare_at_price, "")+ '</s>');
} else {
$('#price-field').html('<span class="product-price">'+ Shopify.formatMoney(variant.price, "") + '</span>' );
}
} else {
// variant doesn't exist.
$('#add').val('Unavailable').addClass('disabled').attr('disabled', 'disabled').fadeTo(200,0.5);
}
}
// initialize multi selector for product
jQuery(function($) {
new Shopify.OptionSelectors("variant-id", { product: , onVariantSelected: selectCallback });
});
// ]]>
</script>
Looking at the code, it looks like you're just missing a product object when you try to initialize the Shopify.OptionSelectors
new Shopify.OptionSelectors("variant-id", { product: , onVariantSelected: selectCallback });
Try adding the product object to this line to see if that fixes the problem. The updated line should look like this:
new Shopify.OptionSelectors("variant-id", { product: {{ product | json }}, onVariantSelected: selectCallback });

Django: Javascript error with alert box displaying values

I am creating a web application that will serve as a grocery store. The way I set it up is so the customer can come onto the website, click on the items that they would like to purchase, and then click a submit button to purchase those items. The problem I am running into is that my Javascript is not printing the correct values. In both spots, it says undefined. I will put a picture below for reference.
views.py
def inventory(request):
products = request.POST.getlist('products')
for product in products:
a = Post.objects.get(title=product)
a.quantity = a.quantity -1
a.save()
print(products)
return redirect('blog-home')
home.html
{% extends "blog/base.html" %}
{% load static %}
{% block content %}
<form action="{% url 'js' %}" method="POST" id="menuForm">
{% for post in posts %}
{% if post.quantity > 0 %}
<article class="media content-section">
<div class="media-body">
<div class="article-metadata">
<a class="mr-2">{{ post.category }}</a>
</div>
<h2><a class="article-title" >{{ post.title }}</a></h2>
<p class="article-content"> Price: ${{ post.Price }}</p>
<p class="article-content"> Sale: ${{ post.Sale }}</p>
<input type="checkbox" id="product_{{ post.id }}" value="{{ post.title }}" form="menuForm" name="products" > Inventory count: {{ post.quantity }}
</input>
</div>
</article>
{% else %}
{% endif %}
{% endfor %}
<button id="btn" type="submit" form="menuForm">Confirm Purchase</button>
</form>
<script src="{% static "JS/javascript.js" %}" type="text/javascript"></script>
{% endblock content %}
javascript.js
function getSelectedCheckboxValues(name) {
const checkboxes = document.querySelectorAll(`input[name="${name}"]:checked`);
let values = [];
checkboxes.forEach((checkbox) => {
values.push(checkbox.value);
});
return values, tPrice;
var price = 0;
var tPrice =0;
if (values=='Milk'){
var MPrice = 3.99
tPrice = price+MPrice;
}
if (values == 'Cheese'){
var CPrice = 4.50
tPrice = price + CPrice;
}
if (values == 'Yogurt'){
var YPrice = 1.99
tPrice = price + YPrice;
}
}
const btn = document.querySelector('#btn');
btn.addEventListener('click', (event) => {
alert('You ordered: ' + getSelectedCheckboxValues('products')+
'\nTotal Price: $'+ getSelectedCheckboxValues('tPrice'));
});
First of all you are passing the parameter to the function getSelectedCheckboxValues as a string when you call them in the alert which is completely wrong.
Also you are directly comparing values list with strings which is not possible. You need to loop over the list and then compare the different elements with the different products. I will also recommend to create an object instead of the list and keep the product name as key and its price as value.

Related products by variant using metafields for Shopify Liquid

I'm trying to build on caroline's solution for related products with metafields to build related product variants. I.e when you click on the white color variant for a desk, you will see the white variant of a chair as a related product. (As opposed to linking the desk product to the chair product regardless of variant.) Caroline's solution is here: https://gist.github.com/carolineschnapp/1003334 and below is my code. Right now it's putting the same product twice on page load, and nothing happens when a different vairant is selected. The way I am formatting the metafield value for each variant is by putting "related-product-handle-1, variant-id-1, related-product-handle-2,variant-id-2, related-product-handle-3, variant-id-3" instead of just the product handles.
{% assign image_size = 'compact' %}
{% assign heading = 'Related Products' %}
{% if product.selected_or_first_available_variant.metafields.recommendations.productHandles %}
<h3>{{ heading }}</h3>
<ul class="related-products"></ul>
{% endif %}
<script>!window.jQuery && document.write('<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"><\/script>')</script>
{{ 'api.jquery.js' | shopify_asset_url | script_tag }}
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
setTimeout(function() {
var dd = $('.single-option-selector#product-select-option-0');
var vId = location.search.substring(9);
switchRelated(vId);
dd.on('change', function() {
$('ul.related-products').empty();
var vId = location.search.substring(9);
switchRelated(vId);
});
function switchRelated(vId) {
var list = $('ul.related-products');
var vIdd = parseInt(vId);
{% for variant in product.variants %}
{% if variantId == vIdd %}
{% if variant.metafields.recommendations.productHandles %}
recommendations = jQuery.trim({{ variant.metafields.recommendations.productHandles | json }}).split(/[\s,;]+/);
for (var i=0; i < (recommendations.length); i+=2 ) {
var j = (i + 1);
if (recommendations.length && recommendations[i] && recommendations[j] !== '') {
jQuery.getJSON('/products/' + recommendations[i] + '.js', function(product) {
product.variants.forEach(function(variant) {
if (variant.id == parseInt(recommendations[j])) {
list.append('<li><div class="image"><img src="' + variant.featured_image.src + '" /></div><h4>' + product.title + '</h4></li>');
}
});
});
}
}
{% endif %}
{% endif %}
{% endfor %}
}
}, 1);
});
</script>
Answer edited: The first was extremely helpful once I made some corrections to syntax errors and a couple of short additions. Here is my edited version of the answer for anyone who may need it:
Product.liquid:
{% for variant in product.variants %}
{% capture metafield_data %}{% endcapture %}
{% assign related_products = variant.metafields.recommendations.productHandles | split: '|' %}
{% for related_product in related_products %}
{% assign metafield_items = related_product | split: ',' %}
{% assign r_p = metafield_items[0] %}
{% assign r_v = metafield_items[1] | plus: 0 %}
{% assign r_n = all_products[r_p].title %}
{% for related_variant in all_products[r_p].variants %}
{% if related_variant.id == r_v %}
{% assign r_i = related_variant.image.src | img_url: 'small' %}
{% endif %}
{% endfor %}
{% capture metafield_data %}{{metafield_data}}{{ r_p }},{{ r_v }},{{ r_i }},{{ r_n }}{% unless forloop.last %}|{% endunless %}{% endcapture %}
{% endfor %}
<option id="{{ variant.id }}" data-metafield="{{ metafield_data }}" {% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money }}- {{ related_products.size }}</option>
{% endfor %}
And related-variants javascript snippet:
$(document).ready(function(){
setTimeout(function() {
var dd = $('.single-option-selector#product-select-option-0');
if(location.search.substring(9) != ''){
var vId = location.search.substring(9);
}
else {
var vId = {{ product.selected_or_first_available_variant.id }};
}
switchRelated(vId);
$('#product-select option').each(function(index, element){
$(".single-option-selector#product-select-option-0 option:eq(" + index + ")").attr('id', element.id);
$('.single-option-selector#product-select-option-0 option:eq(' + index + ')').attr('data-metafield', $(element).attr("data-metafield"));
$('#product-select option:eq(' + index + ')').attr('id', '');
});
dd.on('change', function() {
var list = $('ul.related-products');
$(list).children().remove();
$(list).empty();
if(location.search.substring(9) != ''){
var vId = location.search.substring(9);
}
else {
var vId = {{ product.selected_or_first_available_variant.id }};
}
switchRelated(vId);
});
function switchRelated(vId) {
var list = $('ul.related-products');
$(list).children().remove();
$(list).empty();
var vIdd = parseInt(vId);
console.log(vIdd)
var variant_matches = $('#' + vId).attr('data-metafield').split('|');
for (var i=0; i < variant_matches.length; i++) {
var items = variant_matches[i].split(',');
list.append('<li><div class="image"><img src="'+items[2]+'" /></div><h4>' + items[3].replace('_','') + '</h4></li>');
}
}
}, 1);
});
The only thing I'm nervous about is the fact that I am copying over the data from the 'product-select' dropdown over to the 'single-option-selector' dropdown. I am doing this because there is no template for rendering the single-option-selector, it seems to be getting added through javascript. If anyone has any insight into manipulating the single-option-selector in liquid, please let me know. Thank you!!
The fastest way to implement this is to let Shopify servers structure the elements for to pull links and image URLs with any AJAX calls. Here's how to do it.
From your example of productHandles, I'm guessing the 3 items in the list are related to a particular variant id xxxxxx. Structure the metafield value this way
rph-1,rph-v-id-1|rph-2,rph-v-id-2|rph-3,rph-v-id-3
Now in product liquid find this section
<select class="product-select" id="product-select" name="id" .... </select>
Change the inside html to the one below -
{% for variant in product.variants %}
{% assign related_products = variant.metafields.recommendations.productHandles | split: '|' %}
{% for related_product in related_products %}
{% assign metafield_items = related_product | split: ',' %}
{% assign r_p = metafield_items[0] %}
{% assign r_v = metafield_items[1] | plus: 0 %} {% comment %} converting string to number {% endcomment %}
{% assign r_n = all_products[r_p].title | replace: ' ','_' %}
{% for related_variant in all_products[r_p].variants %}
{% if related_variant.id == r_v %} {% comment %} fails if r_v is a string {% endcomment %}
{% assign r_i = related_variant.image.src }}
{% endif %}
{% endfor %}
{% capture metafield_data %}{{metafield_data}}{{ r_p }},{{ r_v }},{{ r_i }},{{ r_n }}{% unless forloop.last %}|{% endunless %}{% endcapture %}
{% endfor %}
<option id="{{ variant.id }}" metafield-data={{ metafield_data }}{% if variant == product.selected_or_first_available_variant %} selected="selected" {% endif %} value="{{ variant.id }}">{{ variant.title }} - {{ variant.price | money }}</option>
{% endfor %}
"metafield_data" will contain all the related products information (product,variant,variant image).
JS to replace "switchRelated(vId)"
function switchRelated(vId) {
var list = $('ul.related-products');
var vIdd = parseInt(vId);
list.children().remove()
var variant_matches = $('#vId').attr('metafield-data').split('|')
for (var i=0; i < variant_matches.length; i++) {
var items = variant_matches[i].split(',')
list.append('<li><div class="image"><img src="'+items[2]+'" /></div><h4>'+items[3].replace('_','')+'</h4></li>');
}
}
In layman terms, you are taking the product handle and variant id from the metafields and adding title and image to them using liquid (server side function). You are then matching them to variants and assigning a data variable in the element which you are using again to change the html elements.
P.S. The code is long and not properly aligned and I may have missed code punctuations here and there. Please check them. The logic is simple and the entire weight of AJAX is removed and shifted to normal HTML calls.

Change status in ajax on selectbox

I have a question, So ,this code work fine only for the first select box and I dont understand why. For first select box update on database work fine but If I tried to change the statut for the second select box the status remain unchanged. Can you help me? Sorry for my english
My view :
{% for gift in aFilterGifts %}
<form action="" id="updateStatus" method="post">
<select id="statusSelect"
name="{{ gift.id }}"
class="form-control"
onChange="updateCadeauStatus({{ gift.id }})">
{% for key,statut in form_logistique.statut.choices %}
<option value="{{ key }}"
{% if gift.etat == key %}selected="selected"{% endif %}>
{{ statut }}
</option>
{% endfor %}
</select>
</form>
{% endfor %}
<script>
function updateCadeauStatus(id) {
var id = id;
var selectedName = $("#statusSelect option:selected").val();
var url_deploy = 'http:localhost/updateStatus'
console.log(id);
console.log(selectedName);
$.ajax({
url: url_deploy,
type: "POST",
async: true,
data: { id_cadeau:id, id_status:selectedName}
});
}
</script>
The controller :
public function updateStatus(){
$iGiftId = $_POST['id_cadeau'];
$iNewStatus = $_POST['id_status'];
$bUpdate = $this->updateStatusByGiftId($iGiftId, $iNewStatus);
}
The model :
public static function updateStatusByGiftId($iGiftId, $iStatusId){
$request = sprintf( ' UPDATE `%s` set etat = %d WHERE id_instant_gagnant = %d ', $table, $iStatusId, $iGiftId);
return Mysqli::query($request, $database);
}
Thx in advance.
All your select boxes do have the same id id="statusSelect".
That's not valid HTML.
One solution would be to append the gift id to the id tag to create unique ids:
{% for gift in aFilterGifts %}
<form action="" id="updateStatus{{ gift.id }}" method="post">
<select id="statusSelect{{ gift.id }}"
name="{{ gift.id }}"
...
and for the script:
<script>
function updateCadeauStatus(id) {
var id = id,
selectedName = $("#statusSelect" + id + " option:selected").val(),
url_deploy = 'http:localhost/updateStatus';
console.log(id);
...

Hide variants that aren't available in Shopify?

Right now in default Shopify no matter what you select on style you'll still be able to choose any of those sizes even if it's not available for that style. I followed the instructions here: http://wiki.shopify.com/Linked_Options
It works great except that the second option list has duplicated items in it. Any idea why? here is what I have on my product-form.liquid. You can see it in action on my site here: http://gravitypicks.myshopify.com/collections/picks/products/axis
{% if product.available %}
<form action="/cart/add" method="post" class="clearfix product_form shappify_add_to_cart_form" enctype="multipart/form-data" data-money-format="{{ shop.money_format }}" data-shop-currency="{{ shop.currency }}" id="product-form-{{ product.id }}">
{% if settings.display_inventory_left %}
<div class="items_left">
{% if product.variants.first.inventory_management == "shopify" and product.variants.first.inventory_quantity > 0 %}
<p><em>{{ product.variants.first.inventory_quantity }} {{ settings.inventory_left_text | escape }}</em></p>
{% endif %}
</div>
{% endif %}
{% if product.options.size > 1 %}
<div class="select">
<select id="product-select-{{ product.id }}" name='id'>
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %}selected="selected"{% endif %} value="{{ variant.id }}">{{ variant.title }}</option>
{% endfor %}
</select>
</div>
{% elsif product.options.size == 1 and (product.variants.size > 1 or product.options[0] != "Title") %}
<div class="select">
<label>{{ product.options[0] }}:</label>
<select id="product-select-{{ product.id }}" name='id'>
{% for variant in product.variants %}
<option {% if variant == product.selected_or_first_available_variant %}selected="selected"{% endif %} value="{{ variant.id }}">{{ variant.title }}</option>
{% endfor %}
</select>
</div>
{% else %}
<input type="hidden" name="id" value="{{ product.variants.first.id }}" />
{% endif %}
<!-- Bold Apps: Product Options -->
{% include 'shappify-options' %}
{% if settings.display_product_quantity %}
<div class="left">
<label for="quantity">Quantity:</label>
<input type="number" min="1" size="2" class="quantity" name="quantity" id="quantity" value="1" />
</div>
{% endif %}
<div class="purchase clearfix {% if settings.display_product_quantity %}inline_purchase{% endif %}">
{% if settings.cart_return == 'back' %}
<input type="hidden" name="return_to" value="back" />
{% endif %}
<input type="submit" name="add" value="{{ settings.add_to_cart_text | escape }}" class="action_button add_to_cart" />
</div>
</form>
{% if product.variants.size > 1 or product.options.size > 1 %}
<script type="text/javascript">
// <![CDATA[
$(function() {
$product = $('#product-' + {{ product.id }});
new Shopify.OptionSelectors("product-select-{{ product.id }}", { product: {{ product | json }}, onVariantSelected: selectCallback{% if product-form == 'product' %}, enableHistoryState: true{% endif %} });
{% if product.available and product.options.size > 1 %}
Shopify.linkOptionSelectors({{ product | json }});
{% endif %}
});
// ]]>
</script>
{% endif %}
{% endif %}
Here is the JS that is on the page:
<script>
// (c) Copyright 2014 Caroline Schnapp. All Rights Reserved. Contact: mllegeorgesand#gmail.com
// See http://docs.shopify.com/manual/configuration/store-customization/advanced-navigation/linked-product-options
var Shopify = Shopify || {};
Shopify.optionsMap = {};
Shopify.updateOptionsInSelector = function(selectorIndex) {
switch (selectorIndex) {
case 0:
var key = 'root';
var selector = jQuery('.single-option-selector:eq(0)');
break;
case 1:
var key = jQuery('.single-option-selector:eq(0)').val();
var selector = jQuery('.single-option-selector:eq(1)');
break;
case 2:
var key = jQuery('.single-option-selector:eq(0)').val();
key += ' / ' + jQuery('.single-option-selector:eq(1)').val();
var selector = jQuery('.single-option-selector:eq(2)');
}
var initialValue = selector.val();
selector.empty();
var availableOptions = Shopify.optionsMap[key];
for (var i=0; i<availableOptions.length; i++) {
var option = availableOptions[i];
var newOption = jQuery('<option></option>').val(option).html(option);
selector.append(newOption);
}
jQuery('.swatch[data-option-index="' + selectorIndex + '"] .swatch-element').each(function() {
if (jQuery.inArray($(this).attr('data-value'), availableOptions) !== -1) {
$(this).removeClass('soldout').show().find(':radio').removeAttr('disabled','disabled').removeAttr('checked');
}
else {
$(this).addClass('soldout').hide().find(':radio').removeAttr('checked').attr('disabled','disabled');
}
});
if (jQuery.inArray(initialValue, availableOptions) !== -1) {
selector.val(initialValue);
}
selector.trigger('change');
};
Shopify.linkOptionSelectors = function(product) {
// Building our mapping object.
for (var i=0; i<product.variants.length; i++) {
var variant = product.variants[i];
if (variant.available) {
// Gathering values for the 1st drop-down.
Shopify.optionsMap['root'] = Shopify.optionsMap['root'] || [];
Shopify.optionsMap['root'].push(variant.option1);
Shopify.optionsMap['root'] = Shopify.uniq(Shopify.optionsMap['root']);
// Gathering values for the 2nd drop-down.
if (product.options.length > 1) {
var key = variant.option1;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option2);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
// Gathering values for the 3rd drop-down.
if (product.options.length === 3) {
var key = variant.option1 + ' / ' + variant.option2;
Shopify.optionsMap[key] = Shopify.optionsMap[key] || [];
Shopify.optionsMap[key].push(variant.option3);
Shopify.optionsMap[key] = Shopify.uniq(Shopify.optionsMap[key]);
}
}
}
// Update options right away.
Shopify.updateOptionsInSelector(0);
if (product.options.length > 1) Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
// When there is an update in the first dropdown.
jQuery(".single-option-selector:eq(0)").change(function() {
Shopify.updateOptionsInSelector(1);
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
// When there is an update in the second dropdown.
jQuery(".single-option-selector:eq(1)").change(function() {
if (product.options.length === 3) Shopify.updateOptionsInSelector(2);
return true;
});
};
</script>
This link here helped immensely. I had to do some tweaking to fit my uses but it was 99% there for me.
http://docs.shopify.com/manual/configuration/store-customization/advanced-navigation/linked-product-options

Categories