views:

73

answers:

2

i have a asp label in my page .i like to set some text in it with jquery .

<asp:label id="lblError" runat="server" CssClass="error" />

Which method will i use.

$(".error").text('hello'); 
or 
$(".error").html('hello');
or
$(".error").val('hello');

i am confused with all this ?plz help .

+2  A: 

I'd say the most appropriate in this case is

$(".error").text('hello');
  • val(string) it's supposed to be used to set an input control value
  • html(string) should be used to set inner html content and you're just assigning plain text.
Claudio Redi
+1  A: 

If you're using a master page or user control where the clientID will be different than what you defined in your .aspx page or possible that another element shares the same class, another option is:

$("span[id$='lblError']").text('hello');

To specifically answer the question though as noted already .text() is the most appropriate option as all 3 will work. It just semantically makes sense to use .text() to insert text rather than .html() since you are not inserting HTML.

In terms of what actually happens would be another part of the answer now that I think about it a little more, and you can see this yourself by examining the jQuery script itself:

.text() calls javascript function createTextNode with the string passed in and appends to DOM and does little else. //12 lines of code

.html() does more processing for cleaning/processing of the string that is passed in. Also looks to have some code in place to prevent memory leaks. Also uses the innerHTML function of the browser. //38 lines of code

One last note on the difference between .text() and .html() as seen on the API docs to differentiate the two is this line:

Unlike the .html() method, .text() can be used in both XML and HTML documents.
jaywon
+1 Good answer and.... I would like to be right now in Honolulu (everytime I came across with you I think the same!)
Claudio Redi
@Claudio..haha, yea if i could just find a way to not spend every day inside the office :) Argentina not such a bad place to be either from what I hear?
jaywon
@jaywon: not bad at all, true :)
Claudio Redi