IE浏览器中的占位符文本问题(8-9)

时间:2013-11-13 11:03:40

标签: javascript jquery html internet-explorer placeholder

我正在进行表单(输入字段)验证。

问题 - IE浏览器(8-9)将占位符文本视为值,并且在验证期间它接受相同的值,但应将其视为空值。我不想使用任何脚本并实现它,我提出了以下功能。任何人都可以更多地改进功能的可用性/范围。目前,每次用户输入值时,输入字段为空。但是,我希望它首次验证占位符默认文本何时生效。有什么建议吗?

HTML

<input type="text" name="memberid" id="memberid" placeholder="Some Value" />
<a href="#" class="alpha-btn" id="search-btn">Search</a> 

的jQuery

$('#search-btn').on('click', function(){
    if($.browser.msie){
        $('input').each(function() {
            var theAttribute = $(this).attr('placeholder');
            if (theAttribute) {
                $(this).val('');
                alert('Please enter value - IE');
            }
        });
    }
});

2 个答案:

答案 0 :(得分:1)

placeholder< IE 9中产生问题,因此您可以使用data()

<强> HTML

<input type="text" name="memberid" id="memberid" data-placeholder="Some Value" placeholder="Some Value"/>

<强> SCRIPT

$('#search-btn').on('click', function(){
    if($.browser.msie){
        $('input').each(function() {
            var theAttribute = $(this).data('placeholder');
            if (theAttribute == this.value) {// check placeholder and value
                $(this).val('');
                alert('Please enter value - IE');
            }
        });
    }
});

答案 1 :(得分:0)

我认为实现您想要做的最好方法是为IE8和IE9中的占位符构建完整的解决方案。为此,我建议使用Modernizr,并使用输入占位符函数检测。所以,你可以使用这样的函数:

window.ie8ie9placeholders = function() {
  if (!Modernizr.input.placeholder) {
    return $("input").each(function(index, element) {
      if ($(element).val() === "" && $(element).attr("placeholder") !== "") {
        $(element).val($(element).attr("placeholder"));
        $(element).focus(function() {
          if ($(element).val() === $(element).attr("placeholder")) {
            return $(element).val("");
          }
        });
        return $(element).blur(function() {
          if ($(element).val() === "") {
            return $(element).val($(element).attr("placeholder"));
          }
        });
      }
    });
  }
};

这将启用IE8和IE9的占位符。您需要做的就是在初始化代码时使用它。

ie8ie9placeholders();