0

Here is some dynamically generated content with jquery.

<div id="response">
    <button id="high" class="btn-key-main">high</button>
    <button id="last" class="btn-key-main">last</button>
</div>

How do I get the content of the button that is clicked (high or last) in a div with id="solution"? Here's what I tried:

$("#response").on("click", 'button.btn-key-main', function() {
    $("#solution").html($(this).val());
});

Solved by @slicedtoad and @smerny

.val() should've been .html() or .text()

$("#solution").html($(this).html());
5
  • 3
    is response also generated? if so you'll have to either add the listener after creating it or use delegation from a parent that exists at load time Commented Nov 13, 2014 at 18:44
  • @smerny the response div is not generated/it's already present in the DOM. The id's of the response are dynamically generated though. Can you give me an example of what you mean? Commented Nov 13, 2014 at 18:46
  • 1
    Looks like it should work then. Just change val to text() Commented Nov 13, 2014 at 18:47
  • 1
    Okay, I see another problem... try changing $(this).val() to $(this).html()... or text() as I see slicedtoad beat me to this (your buttons do not have values) Commented Nov 13, 2014 at 18:48
  • possible duplicate of how to get text value of calling <button> in jQuery? Commented Nov 13, 2014 at 18:51

2 Answers 2

1

http://jsfiddle.net/o4fyqvk7/

$("#response").on("click", 'button.btn-key-main', function() {
    $("#solution").html($(this).text());
});
Sign up to request clarification or add additional context in comments.

1 Comment

solution was already provided by @slicedtoad, but you get the points
1

$('.selector').val is documented here: http://api.jquery.com/val/

If you want the text of a button use $('.selector').text() http://api.jquery.com/text/

Often it's a good idea to add a values to your buttons. Just use the HTML value='' attribute.

Then you can do things like change the visible language on the button without breaking JS.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.