Show placeholder instead of the default value in html form

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

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?

回答1:

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



回答2:

Provided you are only concerned with browsers that support HTML5, the following is an option:

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


回答3:

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); });


回答4:

<input type="text" name="foo"  placeholder="Foo Name"/> <input type="hidden" name="foo" value="foo"/>


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!