2016-02-12 37 views
2

我有一個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()的值已從其原始狀態更改。這可以使用某種類型的切換功能來完成嗎?

由於提前, 馬克

回答

1

有幾種方法來解決這個問題。你可以使用數據屬性來切換文本,所以我想給你另一個解決方案。

不改變標籤,你可以給它一個使用僞元素的類。因此,您只需稍後刪除該類。

jsfiddle

HTML

<form> 
    <label for="foo" class="required">foo</label> 
    <input type="text" id="foo"> 
</form> 

jQuery的

$('#foo').on('blur', function(){ 
    var inputValue = $.trim($(this).val()); 
    if (inputValue.length == 0){ 
     $('label').addClass('required'); 
    } 
}); 

$('#foo').on('input', function(){ 
    var inputValue = $.trim($(this).val()); 
    if (inputValue.length > 0){ 
     $('label').removeClass('required'); 
    } 
}); 

CSS

label.required::after { 
    content: " - required"; 
} 
+0

這太好了。非常優雅和清晰,感謝您花時間做到這一點。 – marcuthh

1

保存原文的一些屬性的模糊:

$(label).attr('data-original', label.html()); 
$(label).html(label.html() + alert); 

然後輸入其恢復:

var fieldname = $(this).attr('name'); 
var label = $("#registration label[for='"+fieldname+"']");  
$(label).html($(label).attr('data-original')); 
+0

這很好,謝謝你的幫助! – marcuthh

相關問題