jquery checkbox to set input type
I have a html page which requires two passwords, if these do not match a div appears to say so. Within the div a checkbox is also shown when the user checks this it should change the password type to text and vice versa. I seem to be having problems detecting if the checkbox is detected or not.
$("#password_error").html('Passwords do not match <br /> <span class="password_error"><input type="checkbox" id="password_text" /> Show Characters</span>');
$("#password_error").show("slow");
checkbox_status();
function checkbox_status()
{
if ($('#password_text').is(':checked'))
{
$(开发者_如何学运维'input:password[type="text"]');
}
}
The ID on the input box for password is "password".
Any advice? Thanks
You can use:
$('#check').attr('checked');
It will show true or false.
Example
As Dave pointed out, changing the type isn't a good idea, a better idea is to have two inputs, one text and one password. Start with the password showing and the text hidden, that way if javascript is disabled it degrades peacefully. You can then toggle each and update the value on check. Here's a working example:
$(document).ready(function() {
$('#check').click(function() {
if ($(this).attr('checked')) {
$('#plaintext').show().val($('#password').val());
$('#password').hide();
} else {
$('#password').show().val($('#plaintext').val());
$('#plaintext').hide();
}
});
});
http://jsfiddle.net/P8tg5/
working Demo
http://jsfiddle.net/sB9NJ/
html
password: <input type='password' id='password1'><br>
retype password: <input type='password' id='password2'><br>
<div id='messageHolder' style="display:none">
show passwords<input type='checkbox' id='togglePassword' />
</div>
Javascript
jQuery(function(){
jQuery('#password2').bind('blur',_checkPasswords);
jQuery('#togglePassword').bind('change',_togglePasswordText);
});
function _checkPasswords()
{
if(jQuery('#password1').val()!=jQuery('#password2').val())
{
jQuery('#messageHolder').show();
}
}
function _togglePasswordText()
{
if(jQuery('#togglePassword').is(':checked'))
{
jQuery('#password2,#password1').each(function(){
var _elm= jQuery(this);
var _val=_elm.val();
var _id= _elm.attr('id')
jQuery(this).replaceWith('<input id='+_id+' value='+_val+' type="text">')
});
}
else
{
jQuery('#password2,#password1').each(function(){
var _elm= jQuery(this);
var _val=_elm.val();
var _id= _elm.attr('id')
jQuery(this).replaceWith('<input id='+_id+' value='+_val+' type="password">')
});
}
}
精彩评论