How to set placeholder with JS

24,265

Solution 1

@Mohamed Meligy came with the same solution

http://jsfiddle.net/KA85s/8/

Though i used something else..

here is how it works when your input element is created with use jQuery to give it a placholder attribute and we are done :D

** UPDATED **

http://jsfiddle.net/KA85s/19/

added custom default value :D

Solution 2

Use:

input.attr("placeholder", value);

Updated jsfiddle:

http://jsfiddle.net/Meligy/KA85s/5/

In the example I just replaced your val() call, obviously, you can completely remove the part from the function and add it separately with any text you want.

Solution 3

This will do all you need without cross browser compatibility issue i have tested in ie7,8,9 runs perfect.

<input type="text" value="Search" onfocus="if (this.value == 'Search') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Search';}">

good luck!

Share:
24,265
heron
Author by

heron

Updated on June 14, 2020

Comments

  • heron
    heron almost 4 years

    Please take a look at this fiddle:

    http://jsfiddle.net/KA85s/3/

    JQ-UI sets first option as default. I don't want it to be happened: instead I want to set HTML5 placeholder.

    How can I set HTML 5 placeholder (instead of first available <option>) for these JS generated inputs?

    enter image description here

    • James Montagne
      James Montagne about 12 years
      Please include the relevant code within your question.
    • heron
      heron about 12 years
      @JamesMontagne I placed JSfiddle link. Code is huge. No one will read this question without live example
    • James Montagne
      James Montagne about 12 years
      I wasn't saying you should remove the jsfiddle, but it is generally useful to include the relevant code to the question within the question. If jsfiddle ceases to exist, the question should still be useful to others.
  • heron
    heron about 12 years
    You changed whole function. but how to set different placeholder for #qsubject and #qsubject2 ?
  • Leandro Faria
    Leandro Faria about 9 years
    Just a small improvement changing colors as well: onfocus="if (this.value == 'Type your email') {this.value = ''; this.style.color='#333'}" onblur="if (this.value == '') {this.value = 'Type your email'; this.style.color='#BBB'}"
  • Alessandro
    Alessandro over 8 years
    @Aamir Shahzad: thanks! You solved my problem with this cross browser trick! Thanks!