Javascript реализация стрелок в input number - The specified value “NaN” is not a valid number

108
17 марта 2021, 09:40

У меня есть корзина товаров, в которой может быть множество различных сущностей. И я пытаюсь реализовать изменения кол-во товара с помощью input - number без стрелок, а с дополнительными кнопками +/-. И при нажатии этих кнопок у меня выводится ошибка The specified value "NaN" is not a valid number и я не догадываюсь почему. Я знаю что мог бы использовать идентификаторы и с легкостью сделать задуманное. Но в моем случае мне нужно использовать querySelectorAll. Помогите мне пожалуйста подправить данный код. quantity-arrow-minus уменьшает значение поля, а quantity-arrow-plus увеличивает.

<form action="{% url 'cart:cart_update' %}" method="GET">
    <button type="button" class="quantity-arrow-minus">-</button>
    <input type="number" class="update_cart" value="{{item.quantity}}">
    <button type="button" class="quantity-arrow-plus">+</button>
</form>
var minus = document.querySelectorAll('.quantity-arrow-minus');
var update_cart = document.querySelectorAll('.update_cart');
var plus = document.querySelectorAll('.quantity-arrow-plus');
minus.forEach(function(node) {
    node.addEventListener('click', function(e) {
        update_cart.forEach(function(element) {
            element.value = parseInt(update_cart.value - 1);
        });
    });
});
plus.forEach(function(node) {
    node.addEventListener('click', function(e) {
        update_cart.forEach(function(element) {
            element.value = parseInt(update_cart.value) + 1;
        });
    });
});
Answer 1

var minus = document.querySelectorAll('.quantity-arrow-minus'); 
var update_cart = document.querySelectorAll('.update_cart'); 
var plus = document.querySelectorAll('.quantity-arrow-plus'); 
 
minus.forEach(node => { 
  node.addEventListener('click', () => { 
    update_cart.forEach(element => { 
      element.value = parseInt(+element.value - 1); 
    }); 
  }); 
}); 
 
plus.forEach(node => { 
  node.addEventListener('click', () => { 
    update_cart.forEach(element => { 
      element.value = parseInt(+element.value + 1); 
    }); 
  }); 
})
<form action="{% url 'cart:cart_update' %}" method="GET"> 
  <button type="button" class="quantity-arrow-minus">-</button> 
  <input type="number" class="update_cart" value="{{item.quantity}}"> 
  <button type="button" class="quantity-arrow-plus">+</button> 
</form>

Вместо выделенных элементов надо было написать "element" :)

UP

document.body.addEventListener('click', () => { 
  var target = event.target; 
  if (target.tagName != 'BUTTON') return; 
 
  if (target.classList.contains('quantity-arrow-minus')) { 
    target.parentNode.querySelector('input').value = parseInt(+target.parentNode.querySelector('input').value - 1); 
  } 
 
  if (target.classList.contains('quantity-arrow-plus')) { 
    target.parentNode.querySelector('input').value = parseInt(+target.parentNode.querySelector('input').value + 1); 
  } 
})
<form action="{% url 'cart:cart_update' %}" method="GET"> 
  <button type="button" class="quantity-arrow-minus">-</button> 
  <input type="number" class="update_cart" value="{{item.quantity}}"> 
  <button type="button" class="quantity-arrow-plus">+</button> 
</form> 
<form action="{% url 'cart:cart_update' %}" method="GET"> 
  <button type="button" class="quantity-arrow-minus">-</button> 
  <input type="number" class="update_cart" value="{{item.quantity}}"> 
  <button type="button" class="quantity-arrow-plus">+</button> 
</form> 
<form action="{% url 'cart:cart_update' %}" method="GET"> 
  <button type="button" class="quantity-arrow-minus">-</button> 
  <input type="number" class="update_cart" value="{{item.quantity}}"> 
  <button type="button" class="quantity-arrow-plus">+</button> 
</form>

READ ALSO
(x &lt;= 100) тоже самое что и !(x &gt; 100)?

(x <= 100) тоже самое что и !(x > 100)?

На learnjs в тестах был такой вопросик:

71
~ что значит этот символ в javascript?

~ что значит этот символ в javascript?

Что значит данный символ ~ в этом поле?

111
Частичная инициализация вектора

Частичная инициализация вектора

Для последовательной инициализации элементов в вектор их можно добавлять через push_back и emplace_backА что если есть некоторая перестановка индексов,...

92
вывести auto в конструкторе класса

вывести auto в конструкторе класса

Я пытаюсь вывести тип поля класса в конструкторе следующим образом:

92