Hide/Show value text of Input on focus and blur us

2019-08-06 13:12发布

问题:

I have value attribute of an input. I need it to disappear on focus for that particular textbox, and reappear on blur, if the textbox has no content.

This is my current HTML code.

 <label>First Name</label></td>
 <input class="required" type="text" name="firstname" value="Fill" id="firstname" /><span>(required)</span>

Similarly i tried one other thing.When focus is in(Textbox A),a new textbox(B) appears and when focus is out(From A),B gets disappeared.But here is something wrong.I need the user to enter something in Box B also.Now i need something this.When focus is out from A as well B,only then B should disappear. Note:There are number of text box on the page. This is Code for it.

$('#lastname').focusin(function () {
        $('input.hidden').fadeIn(1000);
        $('input.hidden').css('backgroundColor', 'yellow');
        }).focusout(function () {
        $('input.hidden').hide();
        });

Thanks in advance.

回答1:

​$("#firstname")​.on({
    focus: function() {
        if (this.value==='Fill') this.value = '';
    },
    blur: function() {
        if (this.value==='') this.value = 'Fill';
    }
})​;​

FIDDLE

If older browsers are'nt an issue, you don't really need javascript for this:

<label>First Name</label>
<td> 
    <input placeholder="Fill" id="firstname" />
    <span>(required)</span>
</td>​

FIDDLE



回答2:

Try:

$(".required").on("blur", function(){
  $(this).attr("value", "Fill");
}).on("focus", function(){
  $(this).attr("value", "");
});

Jsfiddle



回答3:

var fill = $('#firstname').val();

$('#firstname').on('focus', function() {
    $(this).val('');
}).on('blur', function() {
    if ($('#firstname').val() == "") {
        $(this).val(fill);
    }
});​

Live example



回答4:

<input type="text" id="sample" value="Fill"/>​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​​

You can then use Jquery to handle focus and Blurevent for your textbox

     $('#sample')​.on("focus",function(){
             $(this).val("");
            }).on("blur",function(){
             $(this).val("Fill");
                                       })​;​​

Live Demo