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().toUpperC开发者_开发知识库ase());
alert(mytext);
$("#TestText").val() = $(mytext);
});
Can anyone help me and tell me what's wrong??
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());
});
- http://api.jquery.com/val/
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());
});
Use val()
instead of text()
:
$("#TestText").bind('keyup', function (e) {
$(this).val($(this).val().toUpperCase());
});
I guess this should do it
$("#TestText").bind('keyup', function (e) {
$(this).val($(this).val().toUpperCase());
});
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;
}
精彩评论