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

匿名 (未验证) 提交于 2019-12-03 01:25:01

问题:

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?

回答1:

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.



回答2:

try this :

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


回答3:

I think you have to do that :

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


回答4:

 

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.



回答5:

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

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


回答6:

HTML:

JS:

$("#fname").attr("placeholder", "New placeholder text"); 


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