### 前提
ECサイトの個数変更の個所で、+や-を押すたびに非同期で値を更新したいです。
jsファイルでのidの取得の仕方、記述の仕方がわからないです。
実現したいこと
htmlで表示される要素のidをjsで使用し、最終的に非同期での個数変更がしたいです。
初学者ですがよろしくお願いいたします。
該当のソースコード
js
1counter.js 2 3$(document).ready(function(){ 4 5 window.incrementValue = function (incrementValue) { 6 var value = parseInt(document.getElementById('number_${cart_item.id}').value); 7 value = isNaN(value) ? 0 : value; 8 if(value!=99){ 9 value++; 10 document.getElementById('number_${cart_item.id}').value = value; 11 } 12 } 13 window.decrementValue = function (decrementValue) { 14 var value = parseInt(document.getElementById('number_${cart_item.id}').value, 10); 15 value = isNaN(value) ? 0 : value; 16 if(value>1){ 17 value--; 18 document.getElementById('number_${cart_item.id}').value = value; 19 } 20 } 21 $(function(){ 22 $('input[type="number"]').keyup(function() { 23 if(typeof $(this).attr('min') !== "undefined" && parseInt($(this).val()) < parseInt($(this).attr('min'))) 24 $(this).val($(this).attr('min')); 25 else if(typeof $(this).attr('max') !== "undefined" && parseInt($(this).val()) > parseInt($(this).attr('max'))) 26 $(this).val($(this).attr('max')); 27 else if(typeof $(this).attr('min') !== "undefined" && $(this).val() === '') 28 $(this).val($(this).attr('min')); 29 }); 30 }) 31 32}) 33 34```rails 35_cart_item.html.erb 36 37<table class="table"> 38 <% cart_items.each do |cart_item| %> 39 <tr> 40 <td><%= image_tag cart_item.item.image, size: '110x150' %></td> 41 <td><%= cart_item.item.name %></td> 42 <td>¥<%= cart_item.item.price.to_s(:delimited) %></td> 43 <td id="item_counter_<%= cart_item.id %>"> 44 45 </td> 46 <td> 47 <%= form_with model: cart_item, url: add_item_customers_path, method: :patch do |f| %> 48 <span type="" onclick="decrementValue()" value="-" />-</span> 49 <%= f.number_field :amount, class: "no-spin", min: 1, max: 99, id: "number_#{cart_item.id}", oniput: "value = value.replace(/[^0-9]+/i,'');" %> 50 <span type="button" onclick="incrementValue()" value="+" />+</span> 51 <% end %> 52 </td> 53 <td></td> 54 <td></td> 55 <td></td> 56 </tr> 57 <% end %> 58</table> 59 60
あなたの回答
tips
プレビュー