简体   繁体   English

如何使用确定的类别隐藏或显示最近的跨度

[英]How to hide or show closest span with definite class

I'm trying to validate with min value some required fields. 我正在尝试使用最小值来验证一些必填字段。 I have several inputs. 我有几个输入。 How to make validation to show or hide .min_val for each input - something like closest('.min_val') . 如何进行验证以显示或隐藏每个输入的.min_val类似于closest('.min_val')

I tried: $this('closest').('.min_value').css('display','none'); 我试过了: $this('closest').('.min_value').css('display','none'); , but it's not working. ,但不起作用。 In this case, if I've not filled all inputs, it's showing min_val messages. 在这种情况下,如果我没有填写所有输入,则显示min_val消息。 These messages should be shown for each input independent of the others. 应该为每个输入显示这些消息,而与其他输入无关。 How to do that? 怎么做?

My code is: 我的代码是:

 $(".orders-div :input").each(function () { var min = $(this).attr('data-min-val'); var value = $(this).val(); if(min !== undefined && min !== null && min !== false) { if(value < min) { $(this).addClass('error'); $(this).closest('label').addClass('red'); $('.min_value').css('display','block'); } } 
 <div class="span2"> <label for="quantity"> <?php echo __('Quantity'); ?> <span class="red">*</span> <span class="min_value red" style="display:none"><?php echo __('Required min value:'); ?> 1</span> </label> <input data-min-val='1' class="span12 required" type="text" name="quantity"> </div> 

You can use pure HTML for this: 您可以为此使用纯HTML:

<input type="number" name="quantity" min="1" max="5">

When the form is submitted the browser will check if the input is a number and if it is between 1 and 5. If not it will throw an error. 提交表单后,浏览器将检查输入的数字是否为1到5之间的数字。否则,将引发错误。

http://jsfiddle.net/ydowpz6r/ http://jsfiddle.net/ydowpz6r/

Because of the way the HTML is set up, you need to traverse the DOM to get to the .min_value span that you want. 由于HTML的设置方式,您需要遍历DOM才能达到所需的.min_value范围。

Try this: 尝试这个:

$(".orders-div :input").each(function () {
  var min = $(this).attr('data-min-val');
  var value = $(this).val();

  if(min !== undefined && min !== null && min !== false) {
    if(value < min) {
      $(this).addClass('error');
      $(this).closest('label').addClass('red').find('.min_value').css('display', 'block');
    }
  }

This will find the .min_value span that's contained within the closest label. 这将找到包含在最接近的标签中的.min_value跨度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM