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

2019-08-06 13:39发布

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.

4条回答
孤傲高冷的网名
2楼-- · 2019-08-06 13:41
​$("#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

查看更多
相关推荐>>
3楼-- · 2019-08-06 13:50
var fill = $('#firstname').val();

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

Live example

查看更多
Rolldiameter
4楼-- · 2019-08-06 14:02

Try:

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

Jsfiddle

查看更多
贼婆χ
5楼-- · 2019-08-06 14:05
<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

查看更多
登录 后发表回答