下面的 jQuery 代碼通過將更改事件附加到它來提醒用戶輸入的郵政編碼不正確。我想驗證登錄頁面表單文本欄位中輸入的郵政編碼,并添加一些 HTML 以防提交表單出錯。你能指導我如何做嗎?
輸入的 HTML:
<div class="ff-el-input--content"><input type="text" name="address_1[zip]" id="ff_241_address_1_zip_" class="ff-el-form-control" placeholder="Zip"></div>
jQuery 驗證:
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
return false;
}
});
當驗證失敗時,我需要在input text欄位后面添加下面的 div 。
<div >This field is required</div>
提交元素:
<button type="submit" class="ff-btn ff-btn-submit ff-btn-lg">Submit</button>
顯示部分表格的圖片:

uj5u.com熱心網友回復:
您需要的是函式after()和remove().
jQuery("input:text[name='address_1[zip]']").change(function(e) {
if (!jQuery(this).val().match(/^\d{5}(?:[-\s]\d{4})?$/)) {
alert("Please enter a valid zip code");
jQuery("input[name='address_1[zip]']").val("");
if ($('.error').length == 0) {
$(this).after('<div >This field is required</div>');
}
} else {
$('.error').remove();
}
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/378037.html
標籤:javascript html 查询 前端
下一篇:獲取未定義而不是輸入欄位值
