Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
145 views
in Technique[技术] by (71.8m points)

c# - Retrieve value from asp:textbox with JQuery

I have a few asp:textbox controls in a form on a webpage, below is a snippet. The first is a field where the recipient is entered, the other is a larger textarea where the recipients name should be loaded into, along with some other text.

<asp:TextBox name="recipient" ID="recipient" class="inputBox" onChange="addNames()" runat="server" />
<asp:TextBox TextMode="MultiLine" name="usermessage" ID="usermessage" class="usermessage" height="128" width="425px" runat="server"></asp:TextBox>

A standard message is loaded into this second textbox with use of JQuery with this code:

$(".usermessage").val("Hello etc");

This works nicely, the message is shown.
When a user enters the name of a recipient or his own name in one of the other textboxes, addNames() is triggered. This function adds the name of the recipient to the standard message in the usermessage box.

function addNames() {
    //update textbox
    var recipient = $(".recipient").val();
    var sender = $(".name").val();
    $(".usermessage").val("Hello " + recipient +", 
This is a message. 

Kind regards, 
" + sender);
    }

Problem is that the two variables recipient and sender are "undefined".

Hello undefined,
This is a message.

Kind regards,
undefined




Actual question: What is the correct code to retrieve the value from an asp:textbox if this

var recipient = $(".recipient").val();  

does not work?

The output in the html is as follows:

<input name="ctl00$contentPlaceHolderRightColumn$recipient" type="text" id="ctl00_contentPlaceHolderRightColumn_recipient" name="recipient" class="inputBox" onChange="addNames()" />

I'm using JQuery v1.3.2, with Firefox v3.5.3.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As far as I can tell doing

var recipient = $(".recipient")

Will select all dom elements with a CLASS of recipient. Your input box has a class of "inputBox".

You need to select by its ID using the #

So:

var recipient = $("#recipient")

But you are using ASP.NET controls, which give it a unique ID generated on the server so it's unique. (in your case it's ctl00_contentPlaceHolderRightColumn_recipient)

To select you will need to do

var recipient = $("#<%=recipient.ClientID%>")

-edited out some syntax errors


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...