我有一個HTML試圖使用jQuery驗證的<form>
。到目前爲止,我已經知道如果必填字段留空,某些文本會附加到該字段的關聯標籤上,以通知用戶。這是像這樣做:jQuery - 根據字段輸入切換顯示在標籤上的文本
$(requiredInputs).on('blur', function(){
//isolate name attribute of field left
var fieldname = $(this).attr('name');
//use name value to find associated label to field
var label = $("#registration label[for='"+fieldname+"']");
//sanitize and store current input value in variable
var inputValue = $.trim($(this).val());
if (inputValue.length === 0){
//new div to be appended to the label
var alert = '<p><small>This is a required field!</small></p>';
//change HTML to inform user
$(label).html(label.html() + alert);
//emphasise input box
$(this).css('border', '2px solid red');
}
});
我也儘快有一個事件,消除了紅色的邊框一些文本輸入:
//turn field back to normal on text entry
$(requiredInputs).on('input', function(){
//de-emphasise input box
$(this).css('border', 'none');
});
我想加入到這個活動是爲了擺脫'required field'消息的同時,將標籤返回到其原始文本。我不知道該怎麼做,因爲在添加警告時label.html()
的值已從其原始狀態更改。這可以使用某種類型的切換功能來完成嗎?
由於提前, 馬克
這太好了。非常優雅和清晰,感謝您花時間做到這一點。 – marcuthh