无法弄清楚如何在django电子商务网站中处理产品尺寸,因为不同产品的选择框具有相同的id



这是我的html:

{% if product.id in list_cart %}
<div class="btn-group" style="display: none;">
<select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;"
name="size" required id="sizebox">
{% for t in product.size.all %}
<option value="{{t}}" id="{{t}}">{{t}}</option>
{% endfor %}
</select>
</div>
{% else %}
<div class="btn-group">
<select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;"
name="size" required id="sizebox">
{% for t in product.size.all %}
<option value="{{t}}" id="{{t}}">{{t}}</option>
{% endfor %}
</select>
</div>
{% endif %}

这是我的javascript:

var updateBtns = document.getElementsByClassName('update-cart')
for (i=0;i<updateBtns.length;i++){
updateBtns[i].addEventListener('click',function(){
var productId=this.dataset.product
var action=this.dataset.action

var sizebox = document.getElementById("sizebox");
var size = sizebox.options[sizebox.selectedIndex].value;
console.log(size)

updateUserOrder(productId, action, size)

})
}

我正在做一个基本的django电子商务。网站我遇到了一个我无法解决的问题。问题是,在我网站的产品页面上,每个产品都有一个项目大小的选择框,每个选择框都有相同的id(因为我在迭代产品(。因此,每当我为第一个产品以外的任何产品选择尺寸时,从第一个产品下的第一个选择框中选择的尺寸都会进入我的数据库,而不是该产品下选择的尺寸。我想找出一种方法,将产品下选择框的大小发送到数据库,而不是当前正在发生的id为selectbox的第一个选择框的尺寸。请帮忙。谢谢

尝试使用循环计数器并为select字段生成不同的id,使用loop.index生成值或使用像这样的自定义计数器

counter = 0
{%for ...%}
<option value="{{t}}" id="{{t+counter}}">{{t}}</option>
counter++
{%endfor%}

或者使用loop.index,这是您的代码

{% if product.id in list_cart %}
<div class="btn-group" style="display: none;">
<select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;"
name="size" required id="sizebox">
{% for t in product.size.all %}
<option value="{{t}}" id="{{t+loop.index}}">{{t}}</option>
{% endfor %}
</select>
</div>
{% else %}
<div class="btn-group">
<select class="selection-2 border" data-product={{product.id}} style="border: cadetblue;"
name="size" required id="sizebox">
{% for t in product.size.all %}
<option value="{{t}}" id="{{t+loop.index}}">{{t}}</option>
{% endfor %}
</select>
</div>
{% endif %}

相关内容

最新更新