My add to cart script only works for products where there are multiple options.
jQuery(".button-addtocard").click(function(){
var cur_var = getVariant();
var qty = document.getElementById("qty").value;
addItemToCart(cur_var, qty)
{% comment %} // jQuery(".product-options-bottom #AddToCart-product-template").click(); {% endcomment %}
});
But it doesn’t work for a product where there is one variant, because the product url will be missing the variant id, so I add the following pieces of code:
jQuery(".button-addtocard").click(function(){
var cur_var = getVariant();
console.log(cur_var);
if (!cur_var) {
cur_var = documentgetElementById("one_variant").val;
console.log(cur_var);
}
var qty = document.getElementById("qty").value;
addItemToCart(cur_var, qty)
});
That is, it should take the value from this field, but this does not happen.
How can I fix this?
P.S. in the console, the record is undefined.
There is TypeError in your code try using this code
{% comment %}
{{ product.variants.first.id }} is a better practice than what you are using right now
{% endcomment %}
for you JS file there is a slight mistake
jQuery(".button-addtocard").click(function(){
var cur_var = getVariant();
console.log(cur_var);
if (!cur_var) {
cur_var = document.getElementById("one_variant").value;
console.log(cur_var);
}
var qty = document.getElementById("qty").value;
addItemToCart(cur_var, qty)
});
try using this code if it does not work then we’ll work something out
Thank you for drawing my attention to the error. I managed to get it to work.
jQuery(".button-addtocard").click(function(){
var curr_var = getVariant();
// is undefined or string with id
var one_var = document.getElementById("one_variant");
// is input with value if product has one variant
var cur_var;
console.log(cur_var);
if (typeof curr_var === "string" && one_var === null) {
cur_var = curr_var;
} else {
cur_var = one_var.value;
}
var qty = document.getElementById("qty").value;
addItemToCart(cur_var, qty)
});
Glad to help you if this was helpful kindly mark the reply as an answer