AmbrosiaP AmbrosiaP - 2 months ago 12
jQuery Question

Apply multiple attribute changes to one element

I am using JQuery to make the following changes to one button HTML element. There must be a better way of writing this?

$("#showHide").click(function () {
if ($("#form_password").attr("type") == "password") {
$("#form_password").prop('type', 'text');
$("#showHide").html('Hide');
$("#showHide").removeClass("toggle-hide");
$("#showHide").addClass("toggle-show");
$('#showHide').prop('title', 'Hide Password');
$('#showHide').attr("aria-label","Hide Password");
$('#showHide').attr("aria-pressed","true");

} else {
$("#form_password").prop('type', 'password');
$("#showHide").html('Show');
$("#showHide").removeClass("toggle-show");
$("#showHide").addClass("toggle-hide");
$('#showHide').prop('title', 'Show Password');
$('#showHide').attr("aria-label","Show Password");
$('#showHide').attr("aria-pressed","false");

}
});

Answer

Try this :

$(document).ready(function(){

    $("#showHide").on("click",function(){

        if ($("#form_password").attr("type") == "password") {

            $("#form_password").attr('type', 'text');
            $(this).attr({title:"Hide Password","arria-label":"Hide Password","aria-pressed":"true"});
            $(this).toggleClass("toggle-hide toggle-show").html("hide");
        }

        else {

            $("#form_password").attr('type', 'password');
            $(this).attr({title:"Show Password","arria-label":"Show Password","aria-pressed":"false"});
            $(this).toggleClass("toggle-hide toggle-show").html("Show");

        }

    })
})

Final code :

<!DOCTYPE html>
<html lang="en">
<head>
    <style>
        
    </style>
</head>
    <body>
        <input type="password" id="form_password" value="root"><button id="showHide">Show</button>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
        <script>
            
    $(document).ready(function(){

        $("#showHide").on("click",function(){
            if ($("#form_password").attr("type") == "password") {
                $("#form_password").attr('type', 'text');
                $(this).attr({title:"Hide Password","arria-label":"Hide Password","aria-pressed":"true"});
                $(this).toggleClass("toggle-hide toggle-show").html("hide");
            }

            else {
                $("#form_password").attr('type', 'password');
                $(this).attr({title:"Show Password","arria-label":"Show Password","aria-pressed":"false"});
                $(this).toggleClass("toggle-hide toggle-show").html("Show");

            }

        })

    })
        
        </script>
    </body>
</html>