2

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?

2
  • Place holders (Either the HTML5 version or scripted extensions) are visible when the input control has no value. Jul 23, 2013 at 2:00
  • field will always have a value, assigning a value when creating the text field - its an edit form.
    – Peter
    Jul 23, 2013 at 2:16

4 Answers 4

5

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">
1
  • And if you're concerned with older browsers, the web has some good suggestions for polyfills here and here. These will add support in older browsers with zero/minimal changes to your markup.
    – carpeliam
    Jul 23, 2013 at 2:08
2
<input type="text" name="foo"  placeholder="Foo Name"/>
<input type="hidden" name="foo" value="foo"/>
0
1

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);
});
3
  • 1
    doing it because I like the fact that with placeholder user can just start typing the new value. Instead of selecting and deleting the previous value first. Sry I'm OCD like that! let me try your code..
    – Peter
    Jul 23, 2013 at 2:21
  • Yes, with a placeholder, the user can just start typing a new value. However, you are requesting that the placeholder be forced to show even when the text box already has a value.
    – Brian
    Jul 23, 2013 at 2:28
  • Yes and therefore I made the 'placeholder' equal to the 'value'
    – Peter
    Jul 23, 2013 at 2:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.