jQuery帮助 - 验证

时间:2013-01-12 00:14:31

标签: jquery html css

我正在尝试创建一个允许用户为订单表单输入值的表单。加载表单时,需要突出显示其中没有任何内容的所有行,或者值大于100的行,然后在更正此值时取消突出显示。

此外,还有一个提交按钮 - 当任何文本框突出显示时,需要禁用此按钮

这是我到目前为止的代码 - 有没有人有任何想法?

$(':text').focusin(function() {
    var inp = $(this).val();
    if (inp > 100) {
        $(this).css('background-color', 'red');
    }
    if (inp.length < 1) {
        $(this).css('background-color', 'red');
    }
    if (inp.length > 0 && inp <= 100) {
        $(this).css('background-color', 'white');
    }
});

$(':text').change(function() {
    var inp = $(this).val();
    if (inp > 100) {
        $(this).css('background-color', 'red');
    }
    if (inp.length < 1) {
        $(this).css('background-color', 'red');
    }
    if (inp.length > 0 && inp <= 100) {
        $(this).css('background-color', 'white');
    }
});

3 个答案:

答案 0 :(得分:2)

我建议您在更改元素时向元素添加一个类(即“red_bg”)。这将为您提供简便的方法来确定何时启用提交按钮(即$('.red_bg').length == 0)。

这样的事情应该做:

function validateField(jqSelector) {
    var inp = jqSelector.val();
    var regex = new RegExp(/^\d+$/);
    if (regex.test(inp) && parseInt(inp) <= 100) {
        $(this).removeClass('red_bg');
    } else {
        $(this).addClass('red_bg')
    }
    setSubmit();
}

function setSubmit() {
    $('.red_bg').length == 0) {
        $('#submit_id').removeAttr('disabled');
    }  else {
        $('#submit_id').attr('disabled', 'disabled');
    }
}


$(function () {
    $(':text').focusin(function() {
        validateField($(this));
    }).change(function() {
        validateField($(this));
    }).each(function() {
        validateField($(this));
    });
});

请注意,您可能会考虑使用更深入的验证,因为我现在使用正则表达式,您无需验证输入的值是否为数字。

答案 1 :(得分:0)

我认为这很有效,http://jsfiddle.net/fr85u/

HTML

<form>
  <input />
  <input value="101"/>
  <input value="99"/>
  <button disabled="disabled"> submit </button>
</form>

JS

$('input').each(function(){
  var $this = $(this),
      val = $this.val();

  if(val > 100 || val === ''){
     $this.addClass('red');
  }
}).on('blur', function(){
  var $this = $(this),
      val = $this.val();

  $this.toggleClass('red', val === '' || val > 100);

  $('button').prop('disabled', $("input.red").length > 0);  
});

CSS

.red{
   background-color: red;
}

答案 2 :(得分:0)

由于您的事件处理函数完全相同,您可以将代码重写为

function test() {
    var inp = $(this).val();
    if (inp > 100) {
        $(this).css('background-color', 'red');
    }
    if (inp.length < 1) {
        $(this).css('background-color', 'red');
    }
    if (inp.length > 0 && inp <= 100) {
        $(this).css('background-color', 'white');
    }
};

$(':text').focusin(test).change(test);
test();

第二行将事件处理程序附加到两个事件,最后一行首次执行突出显示功能。

相关问题