change "input type" from text to password

我們在製作版面時對方可能會要求我們的input password會先在欄位內給個輸入的引導文字

,如此讓user能夠知道要針對這個input輸入啥東西,通常這是旁邊沒有說明文字時。

如下圖:


 此時,當您focus進Enter Password欄位內時,就必須改變其type屬性,但是type屬性是不允許

 更改的(會報error),因此可能需要remove掉這個DOM元件,而且還必須在remove掉時,將原

 本元件的id , class等value setAttribute進新的元件內,請見下面的JavaScript code

  1. function replaceT(obj){
  2. if (obj.value == 'Enter Password') {
  3. obj.value = '';
  4. }
  5. var newO=document.createElement('input');
  6. newO.setAttribute('type','password');
  7. newO.setAttribute('onblur',"restoreT(this)");
  8. newO.setAttribute('style',"color:#000000");
  9. newO.setAttribute('id',obj.getAttribute('id'));
  10. newO.setAttribute('class',obj.getAttribute('class'));
  11. obj.parentNode.replaceChild(newO,obj);
  12. newO.focus();
  13. }
  14. function restoreT(obj){
  15. if (obj.value == '') {
  16. var newO=document.createElement('input');
  17. newO.value = 'Enter Password';
  18. newO.setAttribute('type','text');
  19. newO.setAttribute('onfocus',"replaceT(this)");
  20. newO.setAttribute('style',"color:#c9c8c8");
  21. newO.setAttribute('id',obj.getAttribute('id'));
  22. newO.setAttribute('class',obj.getAttribute('class'));
  23. obj.parentNode.replaceChild(newO,obj);
  24. newO.blur();
  25. }
  26. }

您可以看到,我們自訂了兩個function,當focus進帶有文字的元件時會呼叫replaceT,此時

在remove掉原本的text元件時,先將所有的屬性set進新的元件內,之後再remove掉;同理

當blur時,會呼叫restoreT,以此類推。



當初在找尋change type的部分時,意外看到國外的論壇有討論此事,就此分享給大家這個作

法,但我想應該很少網站的輸入機制會這麼囉唆吧囧,當初看到要這麼做有點傻眼orz...

留言