简体   繁体   中英

Show placeholder instead of the default value in html form

A text field in html form have a default value, but I would like to show the placeholder instead of the default value. any ideas?

From what you said here it sounds like you actually want to listen for the focus and blur events and just clear the contents of the <input> with some kind of cache to restore it if nothing gets typed.

<input id="foo" type="text" value="" data-value="" />

Then in script

var foo = document.getElementById('foo');
foo.addEventListener('focus', function () {
    this.setAttribute('data-value', this.value);
    this.value = '';
});
foo.addEventListener('blur', function () {
    if (this.value === '')
        this.value = this.getAttribute('data-value');
});

DEMO

如果您只关心支持HTML5的浏览器,则可以选择以下选项:

<input type="text" name="myText" placeholder="My Placeholder">

On one hand, it is doable; on the other hand, I'm not sure why you should.

$('input[type="text"]').each(function (i, o) {
    var inputBox = $(o),
        swapInValue = function () {
            inputBox.val(inputBox.data('val'));
        },
        swapOutValue = function () {
            inputBox.data('val', inputBox.val()).val('');
        };
    inputBox.blur(swapOutValue).focus(swapInValue);
});
<input type="text" name="foo"  placeholder="Foo Name"/>
<input type="hidden" name="foo" value="foo"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM