Reputation: 54013
I'm building a website in which I use tabs to show different chats. Per tab I've got a dynamically created textarea in which the user can type his message and hit the send button. When I open the first tab, inserting text and hitting the send button works fine. When I open a second tab however, I can't seem to load the text from the textarea anymore.
The function with which I create new tabs looks like this:
function addTab(user_id, name) {
$('#pageTab').append(
$('<li><a href="#' + user_id + '">' + user_id + name +
'<button class="close" type="button">×</button></a></li>'));
$('#pageTabContent').append($('<div class="tab-pane" id="' + user_id
+'"><form id="send_message_form"><textarea id="messageText" rows="3" cols="35"></textarea></br>'
+ '<input type="button" id="sendButton" value="Send Message"></form>'
+ '<div class="conversation"></div></div>'));
$('#page' + user_id).tab('show');
}
and with the following code I try to read the value of the textarea.
$(".response_wrapper").on("click", "#sendButton", function() {
var text = $("#messageText").val(); // Get the text
alert("thetext: " + text);
});
Does anybody know why it can get the value of the textarea in the firstly created tab, but not in the second one? And most importantly; how do I solve this?
Any tips are welcome!
Upvotes: 0
Views: 73
Reputation: 3134
Your issue is likely a result of generating multiple textareas and buttons with the same id
attribute. The id
attribute is meant to be unique for all web elements. I would recommend making some modification so that you have unique ids on your elements, and attach to each textarea you generate. If you don't want to attach to each element when you create them, you might be able to try something like this:
$(".response_wrapper").on("click", "button", function() {
var text = $(this).prev('textarea').val(); // Get the text
alert("thetext: " + text);
});
The above code attaches to buttons generically, instead of a button with a specific id. This should work, although it might result in a execution for every button on the page; your best bet would be to just attach each time you create and append a new element. Note: If you do choose to go with this code, you should still look at using unique ids on your elements. Or, with this code, you don't need ids.
Upvotes: 1