Jquery输入字段验证:如何在输入keypress事件上按类名查找最接近的跨度

时间:2016-11-02 07:26:23

标签: jquery

我想在任何只需要数字的输入的跨度上显示警告消息。我正在使用类来进行跨度,因为我有许多只需要数字的输入。

这是html&的CSS:

    $(document).ready(function () {
      //called when key is pressed in input of class number_only
      $(".number_only").keypress(function (e) {
    		 //if the letter is not digit then display error and don't type anything
    		 if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
    			//display error message
    			$(this).closest('.errmsg').html("Digits and single dot Only").show().fadeOut("slow");
    			return false;
    		 }
       });
    });
    .errmsg {
      color: red;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group" style="">
      <input type="text"  id='input_1' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>
    <div class="input-group" style="">
      <input type="text"  id='input_2' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>
    <div class="input-group" style="">
      <input type="text"  id='input_3' class="form-control number_only">
      <span class="errmsg"></span>	
    </div>

上面的代码没有得到最接近的跨度。请帮忙。

2 个答案:

答案 0 :(得分:1)

size_t const blockIterations = 1; //block call count uint64_t t = dispatch_benchmark(blockIterations, ^{ //your code inside block [self TEST_processJSONDataRecordsWithCompletionHandler:^(id handler) {}]; }); NSLog(@" Avg. Runtime in nanoseconds : %llu ns", t); 搜索父母,closest需要在这里使用

试试这个

.siblings()

jQuery Documentation

答案 1 :(得分:1)

string split function而非next()一起使用。它搜索下一个最近的元素。

Flyout
<Controls:Flyout Height="75"
                 CloseButtonVisibility="Collapsed"
                 IsPinned="False"
                 Position="Bottom"
                 TitleVisibility="Collapsed">
    <TextBlock VerticalAlignment="Center" Text="This is an AppBar" />
</Controls:Flyout>
$(document).ready(function () {
      //called when key is pressed in input of class number_only
      $(".number_only").keypress(function (e) {
    		 //if the letter is not digit then display error and don't type anything
    		 if (e.which != 8 && e.which != 0 && e.which != 46 && (e.which < 48 || e.which > 57)) {
    			//display error message
    			$(this).next('.errmsg').html("Digits and single dot Only").show().fadeOut("slow");
    			return false;
    		 }
       });
    });