2011-06-19 35 views
11

我試圖改變輸入類型,特別是在點擊輸入變更後type =「text」change =「password」使用jQuery(文本 - >密碼)更改輸入字段的類型

我不知道爲什麼,但我不能添加選項type =「密碼」作爲屬性輸入。

 $('input#id_reg_pass').removeAttr("type"); #this works, type="text" is removing 
     $('input#id_reg_pass').attr('type', 'password'); #problem, this not works 
     $(this).addClass('exampleText').val($(this).attr('title')); 

有沒有類似的問題?我會很高興,每一絲... 謝謝

+0

重複的http://stackoverflow.com/questions/1544317/jquery-change-type-of-input-field – thisgeek

回答

6

不能更改屬性type添加元素的DOM後,如果你想讓它發揮作用以同樣的方式在所有瀏覽器,看到thisthis

如Microsoft Internet Explorer 5, 的類型屬性被讀取一次寫入/, 但只有當輸入元件與所述的createElement方法 創建 和之前被添加到 文檔。

13

如果你正在使用jQuery 1.6,用代替.prop

$('input#id_reg_pass').removeAttr("type"); 
$('input#id_reg_pass').prop('type', 'password'); 
$(this).addClass('exampleText').val($(this).attr('title')); 

演示:http://jsfiddle.net/z8Rj3/

+6

將無法​​在IE瀏覽器 – Niklas

+0

@Niklas - 啊, 太糟糕了。 – karim79

+0

謝謝你的回覆。我正在使用[tutorial](http://webservices.blog.gustavus.edu/2008/06/23/text-input-example-text-with-jquery/)。但即使你幫助我(對此感到高興),我仍在努力解決輸入類型=「密碼」和輸入中的文本問題......可以根據需要編輯本教程中的密碼輸入嗎? – user1946705

1

你的代碼拋出錯誤對我來說,type property can't be changed。但有趣的是,下面的代碼並至少對我來說工作在Chrome:

$('input#id_reg_pass')[0].type = 'password'; 

這可能是因爲這不起作用跨瀏覽器然而,這可以解釋爲什麼jQuery的不允許這樣做(正如指出的由Niklas,情況就是如此)。或者,你可以構建一個新的<input>具有相同的屬性,並用它替換舊的。

+0

檢查我的答案。這個錯誤是由jQuery拋出的原因,「這個異常實際上是由jQuery拋出的,所以不是一個錯誤,而是讓編碼器知道不起作用的一個功能。」 – Niklas

+0

@niklas:是的,我看到了你的答案。不幸的是,再次,它只是IE瀏覽器不工作,因爲人們可能會合理預期... –

5

我有完全相同的問題,我想在密碼字段中顯示文本,直到用戶點擊它。我做了另一種方法,而不是嘗試改變字段的類型,我隱藏它並顯示一個新的文本字段,然後調用focus()。它工作正常。

$("#password_fake").focus(){ 
    $(this).hide(); 
    $("#password").show().focus(); 
} 

其中#password_fake是一個文本字段和#password一個style =「display:none」的密碼字段。

+0

這是偉大的,但我得到一個語法錯誤;你的功能不應該在括號內嗎? .focus(function(){...}); –

0

試試這個demo is here

$(document).delegate('input[type="text"]','click', function() { 
    $(this).replaceWith('<input type="password" value="'+this.value+'" id="'+this.id+'">'); 
}); 
$(document).delegate('input[type="password"]','click', function() { 
    $(this).replaceWith('<input type="text" value="'+this.value+'" id="'+this.id+'">'); 
}); 
相關問題