2010-02-16 43 views
3

我已經通過jQuery實現了placeholder HTML 5 attribute不支持它的瀏覽器(除了此時的webkit以外)。通過jQuery實現歌劇的佔位符=「」

它工作得很好,但它有一個小問題:它打破了Opera上的HTML 5 required="required"pattern="pattern"屬性(它是目前唯一支持它們的瀏覽器)。

這是因爲佔位符值暫時被設置爲輸入值,因此Opera在表單提交時認爲輸入實際上是用佔位符值填充的。所以我決定刪除佔位符時提交表單:

$('form').submit(function() { 
    $(this).find(".placeholder").each(function() { 
     $(this).removeClass('placeholder'); 
     $(this).val(''); 
    }); 
}); 

這個工作,但另一個問題出現了:如果窗體客戶端驗證失敗(因爲requiredpattern屬性),那麼字段不重新賦予其佔位值。

那麼,有沒有一種方法(js event?)知道表單提交是否失敗客戶端,所以我可以重新添加佔位符?


測試用例:與支持所需/模式,但不是佔位符(只有Opera在這個時候)瀏覽器中打開this。嘗試提交表單而不填寫任何輸入;你會看到,當你做第二個輸入失去了佔位符。我不希望它發生。


這是完整的代碼,但它可能沒有必要:

function SupportsPlaceholder() { 
    var i = document.createElement('input'); 
    return 'placeholder' in i; 
} 

$(document).ready(function() { 
    if (SupportsPlaceholder()) 
     return; 

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

    $('input[placeholder]').keypress(function() { 
     if ($(this).hasClass('placeholder')) { 
      if ($(this).val() == $(this).attr('placeholder')) 
       $(this).val(''); 
      $(this).removeClass('placeholder'); 
     } 
    }); 

    $('input[placeholder]').blur(function() { 
     if ($(this).val() != '') 
      return; 
     $(this).addClass('placeholder'); 
     $(this).val($(this).attr('placeholder')); 
    }); 

    $('input[placeholder]').each(function() { 
     if ($(this).val() != '' && $(this).val() != $(this).attr('placeholder')) 
      return; 
     $(this).val($(this).attr('placeholder')).addClass('placeholder'); 
    }); 

    $('form').submit(function() { 
     $(this).find(".placeholder").each(function() { 
      $(this).removeClass('placeholder'); 
      $(this).val(''); 
     }); 
    }); 
}); 

回答

3

閱讀:http://dev.opera.com/articles/view/making-legacy-pages-work-with-web-forms/

我沒有嘗試,但它看起來像你可以檢查形式有效性此方式:

if (form.checkValidity){// browser supports validation 
    if(! form.checkValidity()){ // form has errors, 
     // the browser is reporting them to user 
     // we don't need to take any action 

    }else{ // passed validation, submit now 
     form.submit(); 
    } 
}else{ // browser does not support validation 
    form.submit(); 
} 

或者乾脆檢查:element.validity.valid

btw。你還應該爲textarea實現佔位符 - 只需用'input [placeholder],textarea [placeholder]'替換'input [placeholder]'...並且實際上你不需要'佔位符'類;)