Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show password checkbox in ASP.NET MVC 4

how do i show or hide password on click of a checkbox? this is my model class-

    public partial class user
{
    [Required]
    public string username { get; set; }
    [Required]
    [DataType(DataType.Password)]
    public string password { get; set; }
}

And in my View i have done this -

    @Html.EditorFor(model => model.password, new { htmlAttributes = new { @class = "form-control" } })

So now i want to add a checkbox that would show and hide the password.

i searched that it can be done with the help of javascript easily in a webform by changing the 'type' from 'password' to 'text' on the click of checkbox but here in mvc i have mentioned my DataType in the model class. so is there any way that i can change it to text using jquery or javascript?

like image 270
sowmyaa guptaa Avatar asked Apr 19 '16 21:04

sowmyaa guptaa


1 Answers

You can do the same thing in ASP.NET MVC as well since it is client side javascript. Razor uses the attributes to render input elements. Once it is rendered to the browser, you can do anything on the rendered output with client side javascript.

Assuming you have a checkbox with id showPass

@Html.EditorFor(model => model.password, new { @class = "form-control" } )
<input type="checkbox" id="showPass"/>

Now, listen to the change event on this checkbox and if it is true, simply update the input element's type attribute value.

$(function() {

    $("#showPass").change(function() {
        var checked = $(this).is(":checked");           
        if (checked) {
            $("#password").attr("type", "text");
        } else {
            $("#password").attr("type", "password");
        }
    });

});
like image 58
Shyju Avatar answered Oct 09 '22 10:10

Shyju