I'm new to jQuery so this may be a real simple answer. I have a ASP.NET project that I'm trying to dynamically add content to an ASP Label element by typing into a text box and clicking a button. Sounds simple right? Well, I can get the content to added, but when the form is submitted the Label element is still empty? Why is the new data not submitted? What step am I missing? Please help. Here's some sample code:
<asp:Label ID="lblContainer" Text="" runat="server" />
<input type="text" name="tag" id="tag" />
<input type="button" name="AddTag" value="Add" class="button" onclic开发者_StackOverflow中文版k="addTag();" />
function addTag() {
if ($("#tag").val() != "") {
$("#lblContainer").append('$("#tag").val()' + '<br />');
$("#tag").val("");
}
}
Asp.Net doesn't work that way because it won't send the contents of a <span>
tag in the HTTP Post when your form is submitted. You need to add that content to an <input>
of some sort. Try something like this instead.
<span id="tagContainer" runat="server"></span>
<input type="text" name="tag" id="tag" />
<input type="button" name="AddTag" value="Add" class="button" onclick="addTag();" />
<!-- Use a hidden field to store the tags -->
<asp:HiddenField id="tagText" runat="server" />
function addTag() {
var newTag = $.trim($("#tag").val());
if (newTag != "") {
$("#tag").val("");
$("#tagContainer").append(" "+ newTag);
// append the newTag to the hidden field
var $tagText = $("#tagText");
$tagText.val($tagText.val() + " " + newTag);
}
}
Then in your asp.net code you can retrieve the value like so..
string myTagText = tagText.value;
精彩评论