Reputation: 1411
I'm struggling to get the value of a span tag and then pass the value into the input field on click.
$( document ).ready(function() {
$( "input" ).on( "click", function() {
$( ".kb" ).toggle();
});
$( ".kb .row span" ).on( "click", function() {
var key = $('this').text();
alert(key)
$("body").find("input").append(key);
});
});
<input type="text" />
<div class="kb">
<div class="row">
<span>q</span>
<span>w</span>
<span>e</span>
<span>r</span>
<span>t</span>
<span>y</span>
<span>u</span>
<span>i</span>
<span>o</span>
<span>p</span>
<span>[</span>
<span>]</span>
</div>
<div class="row">
<span>a</span>
<span>s</span>
<span>d</span>
<span>f</span>
<span>g</span>
<span>h</span>
<span>j</span>
<span>k</span>
<span>l</span>
<span>;</span>
<span>'</span>
</div>
<div class="row">
<span>z</span>
<span>x</span>
<span>c</span>
<span>v</span>
<span>b</span>
<span>n</span>
<span>m</span>
<span>,</span>
<span>.</span>
<span>/</span>
</div>
Upvotes: 1
Views: 18829
Reputation: 67187
You have totally two mistakes in your code,
remove the quotes surrounded by the this
reference
var key = $(this).text();
input[type=text] is a void element, you are trying to append text into it, so it is invalid.
$("input").val(key); //use .val() instead of .append()
Full code would be,
$(".kb .row span").on("click", function() {
$("input").val($(this).text());
});
For appending the values just use like,
$(".kb .row span").on("click", function() {
var text = $(this).text();
var elem = $('input');
elem.val(elem.val() + text);
});
Upvotes: 3
Reputation: 10736
Your $(this)
reference was wrong and you should use .val() to change inputs value.
$(".kb .row span").on("click", function() {
var key = $(this).text();
alert(key)
$("body").find("input").val(key);
});
Upvotes: 1
Reputation: 104775
this
does not need quotes (else you're literally looking for an element like <this>
):
var key = $(this).text();
Upvotes: 1