Skip to content Skip to sidebar Skip to footer

Adding A Character On A String From A Htmlinput Using Javascript

I have this htmlInput in an ASP:Repeater that I want to be formatted in time format (e.g: 13:39) on its keypress. So far I have this code in repeater databound: Protected Sub rpt_I

Solution 1:

You don't need to declare another variable, you can use the myValue parameter.

I'd recommend to use onchange="kmRun(this)" instead onkeypress="kmRun(this)", because you got to change the content, to finally be formatted by the code.

By using this, you can get all attributes of the textBox control.

You might try something like this, in your javascript code:

functionkmRun(control) {
  control.value = control.value.substring(0, 2) + ":" + control.value.substring(2, control.value.length);
}
<inputid="txt"type="text"onchange="kmRun(this)"value="" />

Solution 2:

There are some problems with your logic.

  • You're sending txt.Value inside your ItemDataBound, but it will be a fixed value when rendered in your HTML, since it will not get updated when the user types. You must change that:

    txt.Attributes.Add("onkeypress", "return kmRun(this.value);")
    

    The keyword this above refers to your input, and whenever the user types, it will get updated.

  • Javascript is not a typed language, there is no String x = declaration. You must use:

    var x = myValue;
    
  • You shouldn't use .substring(0, 2) directly without validating if the field has more than two characters, because if it doesn't, the browser will throw an error.

  • You're using .length as it was a method, but it's a property. Don't use the parenthesis ().


Finally, to pass the value back to your TextBox, you can do:

this.value = x;

Post a Comment for "Adding A Character On A String From A Htmlinput Using Javascript"