2013-09-23 15 views
0

我有一個表單驗證:的jQuery /正則表達式,停止事件使用jQuery /正則表達式冒泡

$(document).ready(function() { 
    $('.keyup-numeric').keyup(function() { 
     $('span.error-keyup-1').hide(); 
     var inputVal = $(this).val(); 
     var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/; 
     if (!numericReg.test(inputVal)) { 
      $(this).after('<span class="tiny warning_bubble">Numeric characters only.</span>'); 
     } 

    }); 
}); 

我如何阻止堆放warning_bubble跨度? 小提琴:http://jsfiddle.net/M2Ns5/ 感謝,

回答

0

可能需要你的HTML的其餘部分產生的警告,並設置爲最初是隱藏的樣式,然後只顯示或隱藏警告時

HTML

<label>Phone Number: 
    <input type="tel" class="keyup-numeric" placeholder="(XXX) XXX-XXXX"/> 
    <span class="tiny warning_bubble">Numeric characters only.</span> 
</label> 

CSS

.warning_bubble { 
    color:#d2232a; 
    -webkit-border-radius: 12px; 
    border-radius: 12px; 
    background-color:#ffdd97; 
    padding:5px; 
    width:100%; 
    display:none; 
} 

JS

$(document).ready(function() { 
    $('.keyup-numeric').keyup(function() { 
     $('span.error-keyup-1').hide(); 
     var inputVal = $(this).val(); 
     var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/; 
     if (!numericReg.test(inputVal)) { 
      $(this).parent().find(".warning_bubble").show(); 
     } else { 
      $(this).parent().find(".warning_bubble").hide(); 
     } 

    }); 
}); 

JSFiddle Demo

0

檢查下一個元素具有&的warning_bubble類然後將其添加跨度。

$(document).ready(function() { 
    $('.keyup-numeric').keyup(function() { 
     $('span.error-keyup-1').hide(); 
     var inputVal = $(this).val(); 
     var numericReg = /^\d*[0-9](|.\d*[0-9]|,\d*[0-9])?$/; 
     if (!numericReg.test(inputVal)) { 
      if (!$(this).next().hasClass('warning_bubble')) { 
       $(this).after('<span class="tiny warning_bubble">Numeric characters only.</span>'); 
      } 
     } else { 
      $(this).parent().find(".warning_bubble").hide(); 
     } 
    }); 
}); 

jsFiddleDemo here

0

的代碼修改最少的是添加一個容器標籤內,輸入後:

<span class="warning-container"></span>  

而且你的後線更改爲空/追加:

$(this).siblings('.warning-container').empty().append('<span class="tiny warning_bubble">Numeric characters only.</span>'); 

注:empty().append()是做html()更快的方式。另外請注意,儘管這是對原始代碼進行的最少更改,但有很多方法可以使其更加高效和更健壯。