[英]Validating multiple inputs with the same ID
我正在我的一家magento商店中開發“按SKU排序”系統。 這是所需SKU和數量的簡單輸入。
我在其中使用以下功能添加了“添加另一個sku”選項:
function adicionarCampos(){
var str = $('tabs-wrapper-cod').insert( '<div class="enc-cod-tab"><span class="enc_cod_02_home">Código: <input type="text" name="cod[]" value="" class="form_carrinho_cod required-entry" /></span><span class="enc_cod_04_home">Qt: <input type="text" name="qt[]" value="" class="form_carrinho_qt required-entry validate-number" /></span></div>' );
}
此功能為用戶添加了另一個“標簽”以輸入另一個SKU。 這是供參考的主要文件:
<div id="enc-cod-conteudo" title="Encomendar por código">
<div class="enc-por-codigo">
<p class="sub-enc-cod">Nunca foi tão simples encomendar por código!</p>
<div class="quick-order">
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="POST">
<div id="tabs-wrapper-cod">
<div class="enc-cod-tab"><span class="enc_cod_02_home">Código: <input type="text" name="cod[]" value="" class="form_carrinho_cod required-entry" /></span><span class="enc_cod_04_home">Qt: <input type="text" name="qt[]" value="" class="form_carrinho_qt required-entry validate-number" /></span></div
</div>
</div>
<div class="actions_carrinho">
<div class="adicionar-cod" onclick="adicionarCampos();"><span>Adicionar código</span></div>
<button style="padding-left: 6px;" type="submit" title="Adicionar" class="button btn-update"><span><span>Adicionar ao carrinho</span></span></button>
</div>
</form>
</div>
</div>
</div>
如您所見,添加的輸入將具有相同的ID“ sku”。 您可以在此處看到驗證腳本要查找的內容:
jQuery(document).ready(function(){
jQuery('#sku').keyup(sku_check);
});
function sku_check(){
var sku = jQuery('#sku').val();
if(sku == "" || sku.length < 7){
jQuery('#sku').css('border', '1px #CCC solid');
jQuery('#tick').hide();
jQuery('#nome_do_produto').hide();
} else {
jQuery.ajax({
type: "POST",
url: "scripts/verificar_cod.php",
data: 'sku='+ sku,
cache: false,
success: function(response){
if(response.length > 0){
console.log(response);
jQuery('#sku').css('border', '1px #090 solid');
jQuery('#tick').fadeIn();
jQuery('#cross').hide();
jQuery('#nome_do_produto').html(response);
jQuery('#nome_do_produto').fadeIn();
jQuery('#codigo_inexistente').hide();
} else {
jQuery('#sku').css('border', '1px #C33 solid');
jQuery('#cross').fadeIn();
jQuery('#tick').hide();
jQuery('#nome_do_produto').hide();
jQuery('#codigo_inexistente').fadeIn();
}
}
});
}
}
現在,我知道這不是正確的方法(ID本質上應該是唯一的),但是javascript並不是我的“海灘”,可以這么說,我一直在堅持如何為添加的輸入賦予唯一的ID,另外,驗證腳本必須查找所有這些遞增的ID。
我的問題是,解決此類問題的最佳方法是什么? 我應該考慮通過javascript遞增嗎? 如果是這樣,怎么辦?
您是對的-ID必須唯一! 向其中添加一個類,例如“ sku-element”,然后使用該類獲取所有元素:
$(".sku-element") //the result set
//or to go over the full result set and work with each item:
$(".sku-element").each(function(){
$(this) //each of the selected items
});
此處不需要ID(您也不應添加ID來進行樣式設置-使用類)。 如果必須具有ID,則可以簡單地創建一個變量來保存當前的元素數量,並且在添加元素更改時,可以隨時更改其ID。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.