简体   繁体   English

影响所有元素的javascript函数

[英]javascript function affecting all elements

I'm trying to develop a shopping cart that allows the user to increase/decrease the quantity of an item in the cart by using a slider. 我正在尝试开发一个购物车,使用户可以使用滑块增加/减少购物车中物品的数量。

Each item in the cart has its own quantity slider. 购物车中的每个项目都有其自己的数量滑块。

The problem is that if there's more than 1 item in the cart, moving the slider for any item other than the first item only affects the quantity of the first item. 问题是,如果购物车中有多个项目,那么移动除第一项目以外的任何项目的滑块只会影响第一项目的数量。 In other words, if I have 2 items in the cart and I use the slider to increase the quantity of the 2nd item, the quantity of the 1st item changes instead of the 2nd. 换句话说,如果购物车中有2件商品,并且使用滑块增加第二件商品的数量,则第一件商品的数量会发生变化,而不是第二件商品的数量发生变化。 The page with the shopping cart is written mainly in php with the function for changing the quantity based on the slider control written in javascript. 购物车页面主要用php编写,具有基于javascript编写的滑块控件更改数量的功能。

What am I doing wrong here? 我在这里做错了什么?

Here is my code for the javascript function: 这是我的javascript函数代码:

    function updateTextInput(val) {
      document.getElementById('textInput').value=val; 
    }

Here is my code for the table cell that calls that function: 这是调用该函数的表格单元格的代码:

<td><input size='3' type='range' name=\"qty[{$row['product_id']}]\" min='0' max='".$stock."' onchange='updateTextInput(this.value);'>
        <input id='textInput' size='3' readonly value=\"{$_SESSION['cart'][$row['product_id']]['quantity']}\"></td>

Thank you for your help. 谢谢您的帮助。

ID of DOM elements have to be unique at whole page. DOM元素的ID在整个页面上必须唯一。 Well, some fix: 好吧,一些修复:

<td>
    <input size='3' type='range' name=\"qty[{$row['product_id']}]\" min='0' max='".$stock."' onchange='updateTextInput(this.value, {$row['product_id']});'>
    <input id='textInput_{$row['product_id']}' size='3' readonly value=\"{$_SESSION['cart'][$row['product_id']]['quantity']}\">
</td>

And fix javascript: 并修复javascript:

function updateTextInput(val, product_id) {
    document.getElementById('textInput_' + product_id).value = val; 
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM