2011-02-16 64 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); 
     } 
    }) 
}