简单的jQuery表单验证:由于占位符polyfill,检查ie9中的空.val()是否失败

时间:2013-05-30 22:25:09

标签: javascript jquery forms internet-explorer internet-explorer-9

新问题/答案

我正在使用HTML5占位符polyfill,它导致ie9将输入的占位符文本设置为值。因此,在HTML5浏览器中,val属性为空,在下面的代码中,ie9将其视为填充。


我正在使用jQuery来确保填写所有字段。这在ie10,webkit和mozilla中工作正常但在ie9中失败。

我在这里做错了什么,为什么这个代码在ie9中不起作用?

谢谢!

$('#quoteform .button.next').on('click',function(){
    var $me = $(this),
        $myParent = $me.parent(),
        $nextStep = $myParent.nextAll('fieldset:not(.disabled)').first(),
        validate;

    // If we're on step2, make sure all fields are filled in            
    if($me.is('#quote-step2 .button') || $me.is('#quote-step1 .button')) {
        $me.parents('fieldset').find('input:visible').each(function(){
            var $me = $(this),
                myVal = this.value;

            if(myVal === '') {
                $me.parent().addClass('warning');
                validate = false;
                return;             
            } else {
                if(typeof validate === 'undefined')
                    validate = true;
            }
        });
    }

    if(validate === false) {
        alert('Please fill out all fields before continuing.');
        return false;
    }

    switchView($nextStep, $myParent);
});

1 个答案:

答案 0 :(得分:2)

我遇到了类似的问题,我的解决方法是除了测试空值之外,还要测试占位符字符串的值。由于polyfill用占位符字符串替换输入的值,因此空值是IE9中占位符的值。

    $me.parents('fieldset').find('input:visible').each(function(){
        var $me = $(this),
            myVal = this.value,
            myPlaceholder = $me.attr('placeholder');

        if(myVal === '' || myVal === myPlaceholder) {
            $me.parent().addClass('warning');
            validate = false;
            return;             
        } else {
            if(typeof validate === 'undefined')
                validate = true;
        }
    });