显示/隐藏占位符文本

时间:2016-05-18 07:21:37

标签: jquery css placeholder

我有几个带有占位符的文本框,例如:

<input class="form-control" id="txtAddress" placeholder="Address" type="text">
<input class="form-control" id="txtZip" placeholder="Zip Code" type="text">

我想在调用SetErrorStateForControl函数时隐藏这些占位符。

var SetErrorStateForControl = function (elemObj, msg) 
{
    $('<span class="reqDiv" name="Required">' + msg + '</span>').prependTo(elemObj.closest('div'));
    //hide placeholders of all textboxes
}

关注焦点我想把占位符放回去。

$("#Offer_Form").find(".form-control").on("focus", function (e) {
        //Show placeholders back
    });

是否可以使用jquery OR css隐藏和显示占位符?

4 个答案:

答案 0 :(得分:2)

HTML:

<input type="text" name="name" placeholder="Enter Text" id="txt1" />

jQuery的:

$('#txt1').focus(function(){
  $(this).attr('placeholder','');
});
$('#txt1').focusout(function(){
  $(this).attr('placeholder','Enter Text');
});

答案 1 :(得分:1)

检查一下。

这可能有助于您理解。

<!DOCTYPE html>
<html lang="en">
    <head>
      <meta charset="utf-8">
      <title>Place Holder</title>
      <script src="https://code.jquery.com/jquery-1.10.2.js"></script>
    </head>
    <body>
        <div id=Offer_Form>
            <input class="form-control MyClass" id="txtAddress" placeholder="Address" type="text">
            <input class="form-control MyClass" id="txtZip" placeholder="Zip Code" type="text">    
        </div>
    <script type="text/javascript">


        $(document).on("focus" , ".MyClass" , function () {

            $(this).removeAttr('placeholder');

        });

        $(document).on("focusout" , ".MyClass" , function () {

            if($(this).val() == ''){
                $(this).attr('placeholder' , "My PlaceHolder");
            }

        });

    </script>

    </body>
</html>

答案 2 :(得分:0)

<input type="text" placeholder="enter your text" onfocus="this.placeholder = ''" onblur="this.placeholder = 'enter your text'" />

答案 3 :(得分:0)

尝试一下。

$("input").each(
            function(){
                $(this).data('holder',$(this).attr('placeholder'));
                $(this).focusin(function(){
                    $(this).attr('placeholder','');
                });
                $(this).focusout(function(){
                    $(this).attr('placeholder',$(this).data('holder'));
                });
                
        });
li{padding:15px;list-style-type: none;}
input{padding:8px;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
    <ul class="field-set field-set-stacked">
       <li class="field field-text">
           <input type="text" placeholder="Enter your name" />
       </li>
       <li class="field">
           <input type="text" placeholder="Enter your email address" />
       </li>
       <li class="field">
           <input type="text" placeholder="Enter amount" />
       </li>
    </ul>                  
</form>