1

I am working on a webforms project using c#/aspx/jquery. I'm not sure where to handle my Onclick. Both options (doing it in C# or jquery) seem feasible. Which would be better practice?

Here is the scenario:

I want to build a checkbox which will toggle a textbox's textmode, altering it between Password and SingleLine.

Currently, I have this following code for my markup since I am currently handling it in C#:

<asp:Checkbox ID="CheckBox1" OnCheckedChanged="CheckBox1_OnCheckedChanged"/>

The code:

protected virtual void OnCheckedChange(EventArgs e)
{
     If (CheckBox1.TextMode == TextMode.Password)
          CheckBox1.TextMode = TextMode.SingleLine;
     else
          CheckBox1.TextMode = TextMode.Password;
}

The use case of this is: A user is entering his password. On the same page, he may choose to keep the password hidden or not by checking the checkbox.

Rhs
  • 2,896
  • 10
  • 38
  • 78
  • You probably want to do this in jQuery as it is client logic and you don't want/need a postback. This post may help: http://stackoverflow.com/questions/3541514/jquery-change-input-type – MikeSmithDev Jan 29 '13 at 15:47

2 Answers2

2

Which would be better practice?

What is your functional requirement?

  • Setting this in C# on the asp.net code behind, you will need a post-back to make it work. This means the page will refresh and the text box will change.
  • On the client (JS/JQuery) the page will not refresh.

Now you evaluate the work required vs the quality you need. (If you want a nice user experience and are ok with writing JS put it in JS, if you're strapped for time and are ok with the refresh then do it on asp.net).

I'm trying to answer your question in general sense about HOW such a decision (in my humble opinion) should be made. Realistically this is very simple to implement in javascript and your should do it there.


Now for the code (I assume you know how to put it in asp.net code behind so I'm going to write the JS approach):

Html:

My Password: <input type="password" id="mytext" /> <br />
Hide Chars : <input id="passChk" type="checkbox" checked="true" />

Javascript:

$(function() {
    $("#passChk").change(function(){
        if(this.checked) {
            $("#mytext").attr("type","password");
        } else {
            $("#mytext").attr("type","text");
        }
    });
});

See it running here: http://jsfiddle.net/rC5NW/2/

gideon
  • 18,841
  • 10
  • 69
  • 110
0

After trying to implement the accepted answer, I realized that some browsers (I used Google Chrome) does not allow changing the type attribute. There is a way to bypass this but I don't think it is worth it for my purposes:

Therefore, It might be better to just use C#.

Relevant Questions

Community
  • 1
  • 1
Rhs
  • 2,896
  • 10
  • 38
  • 78