JavaScript - uncheck check box on mouseup

家住魔仙堡 提交于 2020-01-16 18:47:07

问题


I'm trying to implement a simple 'show password' toggle check box so that whilst the mouse is held down, the plain text password is shown, and once it's let go it reverts back to a password field.

I've got the toggle of the input field working, however I'm using a check box to show the toggle state as well, and I can check the box on mousedown however my attempt at then unchecking the box is not quite working.

Here's what I've got so far;

DEMO

var pwi = $('#new_pass');

$('.pw_show').on('mousedown', function () {
    $('.pw_show input').prop('checked', true);
    pwi.prop('type', 'text');
});

$('.pw_show').on('mouseup', function () {
    pwi.prop('type', 'password');
    setTimeOut(function() {
        $('.pw_show input').prop('checked', false);
    }, 50);
});

This almost works, however if the user double clicks quickly then they can break it leaving the checkbox checked. Is there a better way to do this?


回答1:


Use this:

$(".pw_show input").attr("checked","");



回答2:


It works correctly, but this works only for .pw_show. So if you mouseup at the another layer, it does not work. I noticed that your Input has not stable width.

You can either use removeAttr:

$(".pw_show input").removeAttr("checked");



回答3:


Use change event in jquery to to check a check box ,based on that you change the text box type

    var pwi = $('#new_pass');
      $('.pw_show').find("input[type=checkbox]").on('change', function () {
           pwi.prop("type", (this.checked) ? "text" : "password");

      });

UPDATED DEMO

If you want mousedown and mouse up,use like this

 var pwi = $('#new_pass');

$('.pw_show').find("input[type=checkbox]").mousedown('change', function () {
    pwi.prop("type",  "text" );

});
$('.pw_show').find("input[type=checkbox]").mouseup('change', function () {

    pwi.prop("type",  "password");

});

USING MOUSEDOWN/MOUSEUP




回答4:


The problem with my code was the spelling of the setTimeout function. After fixing this, the small delay I added, allowed the check box to be checked and unchecked on click hold and release.

$('.pw_show').on('mouseup', function () {
    pwi.prop('type', 'password');
    setTimeout(function() {
        $('.pw_show input').prop('checked', false);
    }, 50);
});

Fixed Fiddle



来源:https://stackoverflow.com/questions/24993978/javascript-uncheck-check-box-on-mouseup

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!