Changing the “placeholder” attribute of HTML5 input elements dynamically using Javascript

StackOverflow https://stackoverflow.com/questions/3919369

  •  29-09-2019
  •  | 
  •  

Question

I'm trying to dynamically update the HTML5 placeholder attribute of a text field using jQuery.

$("textarea").attr("placeholder", "New placeholder text");

From Firebug, I can observe that the placeholder attribute is indeed changing. But in the rendered textarea element, it stays the same. Any suggestions?

Was it helpful?

Solution

If you are using Firebug I can assume you are using Firefox, and Firefox doesn't yet support placeholder attribute in the input fields itself.

Placeholder feature detection

I just tried on Chrome for Mac and it supports placeholder text on textareas (and changes via javascript)

2015 Update: sometimes I gain reputation for this answer, so I want to clarify that this was accepted as correct because at the time Firefox 3.6 didn't support placeholder attribute. Release 4 then added support ("fixed the issue" wouldn't have been fair) so the code of OP works as expected since then.

OTHER TIPS

try this :

$('#inputTextID').attr("placeholder","placeholder text");

I think you have to do that :

$("textarea").val('');
$("textarea").attr("placeholder", "New placeholder text");
<label for="myname">Name *</label>
<input type="text" name="myname" id="myname" title="Please enter your name"
       pattern="[A-Za-z ]+, [A-Za-z ]+"
       autofocus required placeholder="Last, First" />

Then you want to select the placeholder and replace that text with the new text that you want to enter.

$("input[placeholder]").attr("placeholder", "This is new text");

This will replace the text of Last, First to This is new text.

working example of dynamic placeholder using Javascript and Jquery http://jsfiddle.net/ogk2L14n/1/

<input type="text" id="textbox">
 <select id="selection" onchange="changeplh()">
     <option>one</option>
     <option>two</option>
     <option>three</option>
    </select>

function changeplh(){
    debugger;
 var sel = document.getElementById("selection");
    var textbx = document.getElementById("textbox");
    var indexe = sel.selectedIndex;

    if(indexe == 0) { 
     $("#textbox").attr("placeholder", "age");

}
       if(indexe == 1) { 
     $("#textbox").attr("placeholder", "name");
}
}

HTML:

<input type="text" placeholder="entername" id="fname"/>

JS:

$("#fname").attr("placeholder", "New placeholder text");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top