IE8在验证失败后删除占位符文本

时间:2014-02-12 10:54:20

标签: jquery forms internet-explorer-8 placeholder polyfills

与此question

有类似的问题

在所有浏览器中,占位符文本在我的表单上验证失败后很好,但它在IE8中消失了。最初IE8没有显示占位符,因此我使用此修复程序填充占位符

$('[placeholder]')
    .focus(function () {   
        var input = $(this);   
        if (input.val() == input.attr('placeholder')) {  
            input.val('');   
            input.removeClass('placeholder');   
        }   
    })
    .blur(function () {   
        var input = $(this);   
        if (input.val() == '' || input.val() == input.attr('placeholder')) {   
            input.addClass('placeholder');  
            input.val(input.attr('placeholder'));   
        }  
    })
    .blur();   

$('[placeholder]').parents('form').submit(function () {    
    $(this).find('[placeholder]').each(function () {   
        var input = $(this);   
        if (input.val() == input.attr('placeholder')) {   
            input.val('');   
        }  
    })   
});

我是否应该首先使用不同的占位符修复/ polyfill?或者有办法解决这个问题吗?

3 个答案:

答案 0 :(得分:1)

    var placeholders = {};
$('form').validate({
   submitHandler: function(form) {

   $(form).find(':input[placeholder]').each(function() {
      var placeholder = $(this).attr('placeholder'); 
      placeholders[placeholder] = this;
      $(this).removeAttr('placeholder');
   });       

   form.submit();


 },



enter code here

  $.each(placeholders, function(placeholder, element) {
      $(element).attr('placeholder', placeholder);
  });

}

});

答案 1 :(得分:0)

在不支持占位符的浏览器中尝试使用此库作为占位符。

https://github.com/mathiasbynens/jquery-placeholder

答案 2 :(得分:0)

我通过重新定义验证器的默认所需函数解决了这个问题。在调用验证之前我添加了这个:

    jQuery.validator.addMethod("required", function(value, element, param) {
        // check if dependency is met
        if ( !this.depend(param, element) ) {
            return "dependency-mismatch";
        }
        if ( element.nodeName.toLowerCase() === "select" ) {
            // could be an array for select-multiple or a string, both are fine this way
            var val = $(element).val();
            return val && val.length > 0;
        }
        if ( this.checkable(element) ) {
            return this.getLength(value, element) > 0;
        }
        default:
            var placeholderval = $(element).attr('placeholder');
          //if some placeholder values are actually default values, just use "default" attribute to mark them
            var defaultvar = ($(element).attr('default') === undefined);
            return ($.trim(value).length > 0 && ($.trim(value)!=$.trim(placeholderval) || !defaultvar));
    }, jQuery.validator.messages.required);