Reputation: 342
How can I get the value to the input that was clicked? At the moment the value shows in all inputs. How can I show the value in the selected input?
Here is my code:
$('.ui-spinner').click(function () {
$('.cn-wrapper').show();
});
$(".cn-wrapper li span").click(function () {
var textValue = $(this).text();
$('.ui-spinner').val(textValue);
});
.cn-wrapper {
display:none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cn-wrapper" id="cn-wrapper">
<ul>
<li><a href="#"><span >50</span></a></li>
<li><a href="#"><span>100</span></a></li>
<li><a href="#"><span>200</span></a></li>
<li><a href="#"><span >300</span></a></li>
<li><a href="#"><span >400</span></a></li>
<li><a href="#"><span >500</span></a></li>
<li><a href="#"><span>600</span></a></li>
<li><a href="#"><span>700</span></a></li>
<li><a href="#"><span>Set</span></a></li>
</ul>
</div>
<input id="user1" class="ui-spinner"></input>
<input id="user2" class="ui-spinner"></input>
<input id="user3" class="ui-spinner"></input>
Here is an external fiddle.
Upvotes: 1
Views: 76
Reputation: 1532
One way to do it would be to create a variable outside of your click listeners that references the lastClickedInput
like so:
var lastClickedInput = null;
$('.ui-spinner').click(function () {
$('.cn-wrapper').show();
lastClickedInput = $( this );
});
$(".cn-wrapper li span").click(function () {
var textValue = $(this).text();
if ( lastClickedInput )
lastClickedInput.val( textValue );
});
Example Fiddle: https://jsfiddle.net/richardgirges/fmLjr5cf/6/
Upvotes: 1
Reputation: 337691
You would need to store the last clicked input
in a variable which is in scope of both functions, something like this:
var $target;
$('.ui-spinner').click(function () {
$('.cn-wrapper').show();
$('.target').removeClass('target');
$target = $(this);
});
$(".cn-wrapper li span").click(function () {
var textValue = $(this).text();
$target.val(textValue);
$('.cn-wrapper').hide();
});
Alternatively, you could add a class to the selected input on click and then target that when setting the value:
$('.ui-spinner').click(function () {
$('.cn-wrapper').show();
$(this).addClass('target');
});
$(".cn-wrapper li span").click(function () {
var textValue = $(this).text();
$('.target').val(textValue);
});
Upvotes: 5