views:

44

answers:

1

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" onclick="addTag();" />


function addTag() {
    if ($("#tag").val() != "") {
        $("#lblContainer").append('$("#tag").val()' + '<br />');
        $("#tag").val("");
    }
}
+2  A: 

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;
jessegavin
So the snag with that answer is that I simplified my example. Actually, with each tag I add I'm also adding a button that can be clicked to remove the element from the list (onclick="($(this).parent().remove()))So I guess the new question here would be, how would I keep this hiddenfield value up to date when the user can delete any tag they wish?!
YourMomzThaBomb
You should update your question then.
jessegavin
I did. An ASP Label should be updating/submitting right?! I must be missing something silly.
YourMomzThaBomb