tags:

views:

23

answers:

4

I have written a short jquery method that on the keypress event of a text box should change the textbox content to upper case. The method fires and teh alerts show but the case of the text never changes to upper case.

Here is the jquery method

$("#TestText").bind('keyup', function (e) {
    var mytext = $("#TestText").val();
    $(mytext).text($(mytext).text().toUpperCase());
    alert(mytext);
    $("#TestText").val() = $(mytext);
});

Can anyone help me and tell me what's wrong??

+1  A: 

Use val() instead of text():

$("#TestText").bind('keyup', function (e) {
    $(this).val($(this).val().toUpperCase());
});
Sarfraz
+4  A: 

To refer to the element that received the event, you use this.

What you were doing was taking the text, and wrapping it in $() as though you were selecting an element.

Then you were using an improper use of .val() by doing = $(mytext).

jQuery's .val() method has two uses. With no arguments it gets the value. With an argument, it sets the value.

$("#TestText").bind('keyup', function (e) {
        // get the value of the input
    var mytext = $(this).val();
        // set the value of the input
    $(this).val(mytext.toUpperCase());
});

EDIT: It is always a good idea to cache jQuery objects that are reused.

$("#TestText").bind('keyup', function (e) {
    var $th = $(this);
        // get the value of the input
    var mytext = $th.val();
        // set the value of the input
    $th.val(mytext.toUpperCase());
});
patrick dw
A: 

I guess this should do it

$("#TestText").bind('keyup', function (e) {
    $(this).val($(this).val().toUpperCase());
});
Aldo
A: 

this should work:

$("#TestText").bind('keyup', function (e) {
  $("#TestText").val($(this).val().toUpperCase());
});

but i'd use css property text-transform and set it to

  #TestText {
    text-transform:uppercase;
  }