2011-02-16 65 views
2

有沒有辦法在頁面上添加複選框或單選按鈕來切換輸入類型「文本」和「密碼」之間的表單字段?切換窗體字段類型與jQuery

我把jQuery放在主題行中的原因是因爲我試圖獨佔使用它,並且我對它的潛力有很大的信心。 :)

謝謝。


更新: 我需要切換,因爲我需要的用戶回來查看以前輸入的輸入的能力。 (提示:這不是登錄腳本。)

回答

3

你會想用一個聰明的小jquery來完成這個錯覺。

現場演示:http://jsfiddle.net/aaK9E/2/

考慮下面的HTML/CSS:

HTML

<input type="text" size="50" id="t" name="passtext" /> 
<input type="password" size="50" id="p" name="passpass" /><br /> 
<input type="checkbox" id="c">Show Password 

CSS

#t{display:none;} 

您可以使用複選框作爲一個切換這樣

var showPass=false; 
$('#c').change(function(){ 
    showPass = ($('#c:checked').length>0); 
    if (showPass){ 
     $('#p').hide(); 
     $('#t').show(); 
    }else{ 
     $('#t').hide(); 
     $('#p').show(); 
    } 
}); 

現在,你需要確保兩個文本框始終具有相同的值。當一個變化時,你想改變另一個,反之亦然。對於那些你需要使用下面的JS

$('#p').change(function(){ 
    if (!showPass) //password box is showing. sync its value to the textbox 
     $('#t').val($('#p').val()); 
}); 
$('#t').change(function(){ 
    if (showPass) //textbox is showing. sync its value to the password box 
     $('#p').val($('#t').val()); 
}); 

如果同時passtextpasspass都以相同的形式,他們都將被傳遞到接收器,並且它們都將具有相同的價值,因爲我們synching他們使用(例如使用PHP)$variableName = $_REQUEST['passpass'];

1

您無法將字段類型從密碼更改爲文本,反之亦然。你可以在彼此頂部創建一個密碼和文本字段,並用單選按鈕改變字段的可見性/ z-索引

+0

怎麼樣,雖然名字?他們會同時提交?爲什麼不能這樣做?我幾乎可以肯定我看到它在某處實施。如果的確如此,那麼我可以使用.load()從外部文件中獲取適當的類型字段,對吧?聽起來很複雜 – santa 2011-02-16 17:20:42

+0

這是我所知道的唯一解決方案(並且正在使用我自己)......您不必在頁面上具有TEXT字段,就可以使用jQuery將其添加到密碼字段的位置,然後刪除密碼字段...當複選框未被選中時,進行相反的過程...就像一個魅力;-) – 2011-02-16 18:07:11

+0

安全是原因。正如你知道的大多數瀏覽器明星密碼。如果設置了一個腳本來恢復用戶的這種效果,那麼您更可能站在他們的肩膀上,並閱讀用戶密碼 – 2011-02-16 19:03:24

7

我結束了簡化成以下的解決方案是:

$('input#checkbox').change(function(){ 
    var type = ($(this).is(':checked') ? 'text' : 'password'), 
     input = $('input#password'), 
     replace = input.clone().attr('type', type) 
     input.replaceWith(replace); 
}); 
0

我回答過類似的問題在這個thread

解決方案是一個支持多個密碼字段的jQuery插件(我寫的)。來源張貼於github

使用範例:

<input type="password" id="inputGroup1"> 
<input type="password" id="inputGroup2"> 
<label> 
    <input type="checkbox" class="input-mask" data-toggle='["inputGroup1", "inputGroup2"]'>Toggle Password 
</label> 
<script> 
$('.input-mask').passwordToggle(); 
</script> 
1
instead of cloning input type, you can use the simple logic of toggling. 
handle--> the button which will cause event. 
target--> target input on which you want the toggle to happen. 
event type--> event name on which given button will cause toggle on target. 
typeChange--> name of type which you want to alter example "text" if you want password type to text type. 

    function type_toggle(handle, target, eventType, typeChange) { 
    var targetType = $(target).prop("type"); 
    $(handle).on(eventType, function() { 
     if ($(target).prop("type") !== typeChange) { 
      $(target).prop("type", typeChange); 
     } else { 
      $(target).prop("type", targetType); 
     } 
    }) 
}