jQuery forEach() 和 change() 函数来隐藏<select>和显示输入



我有这个表单。我在Laravel工作,问题是当用户在+10中选择选项时,必须隐藏select字段,并显示购物车中每个产品的input字段。

<td class="text-center">
<form action="{{ route('cart.update') }}" method="POST" id="QtyRefresh">
@csrf
@if($detail->quantity >= 10)
<input type="number" name="quantity2" class="inputQty" id="qtyInput2" value="{{ $detail->quantity }}" autofocus>
@else
<select name="quantity" id="qtySelect{{ $detail->id }}" class="selectQty">
<option {{old('quantity',$detail->quantity)=="1"? 'selected':''}} value="1">1</option>
<option {{old('quantity',$detail->quantity)=="2"? 'selected':''}} value="2">2</option>
<option {{old('quantity',$detail->quantity)=="3"? 'selected':''}} value="3">3</option>
<option {{old('quantity',$detail->quantity)>="10"? 'selected':''}} value="+10">+10</option>
</select>
@endif
<input type="hidden" name="cart_detail_id" id="cartId{{ $detail->id }}" value="{{ $detail->id }}">
<input type="hidden" name="quantity" id="qtyInput{{ $detail->id }}" class="inputQty" value="{{ $detail->quantity }}" autofocus>
</td>
<td id="tdQtyForm">
<a href="#" onclick="document.getElementById('QtyRefresh').submit()">
<i class="material-icons" rel="tooltip" title="Actualizar Cantidad">refresh</i>
</a>
</td>
</form>

jQuery

$(document).ready(function(){
//var CartDetailId = '{{ $detail->id }}';
var allSelect = document.querySelector("#CartTable").querySelectorAll("select");
console.log(allSelect);
allSelect.forEach(function(element){
$(this).change(function()){
if(element.value === '+10'){
$('#qtySelect').remove();
$('#qtyInput').attr('type', 'number').show().focus();
}
}
});
});

产品表图像

不需要使用forEach()并为每个单独的选择添加事件处理程序。无论是为了性能还是简单性,最好只添加一个与每个select匹配的事件处理程序,并使其工作并针对正确的元素。

您的问题没有具体说明,但从代码中可以看出,您有一系列select输入,每个输入都有不同的$detail->id。由于您要处理的select和隐藏的input都在其HTML ID属性中使用该ID值,因此我们可以使用该值来针对正确的元素。

这是一个正在工作的JSFiddle。

$(document).ready(function(){
// Handle changes on *every* select on the page
$('select').on('change', function() {
// Find the id of the select that was changed
var id = $(this).attr('id'); 
// Find the $detail->id of the select that was changed
var detailID = id.replace('qtySelect', '');
// Check the value selected
if ($(this).val() === '+10') {
// Show the input field with the matching $detail->id
$('#qtyInput' + detailID).attr('type', 'number').show().focus();
// Hide the select.  If you .remove() it, you can't re-display it 
// if the user changes their selection back to 9 for example.
$(this).hide();
}
});
});

一些注意事项:

  • 您的代码混合使用纯JS和jQuery。从技术上讲,这并没有错,但它确实让阅读和维护变得更加困难。如果您要在包含jQuery(额外的http查询、额外的页面加载时间等(方面受到打击,并且要麻烦编写一些jQuery代码,那么您还可以使用它,同时使代码更简单、更一致。

  • 如果你的隐藏输入只是用CSS隐藏的,它看起来更整洁、更简单,我的意思是它不一定是type=hidden。你的JS只是在改变表现形式,这就是CSS的作用。

  • 同样,简单地隐藏select可能比直接remove()要好,但这可能取决于您的需求。

  • 最后,为了将来的参考,如果你能尝试创建一个最小、完整和可验证的例子,这将使其他人更容易提供帮助。在您的案例中,问题是100%关于jQuery。我们不需要看到你的刀片,PHP,Laravel的东西。我们所需要的只是生成的HTML。类似地,#qtyInput2不相关,cart_detail_id也不相关,刷新内容也不相关。。。。陈述问题越简单,阅读、理解和回答问题就越简单

最新更新