Reputation: 185
I am trying to add value to input field by clicking on choices that are open on click. I have this html that output input field
<div class="country first-country col-md-3">
<input type="text" id="country1" placeholder="Select country/region" value="">
<ul id="country-list" class="country-list">
<li><a href="#">Spain</a></li>
<li><a href="#">France</a></li>
</ul>
</div>
and when you click on input field, dropdown with choices is opened, and then when I click on Spain, value spain should be added to input.
$('.country-list').hide();
$( ".first-country").find('input').focus(function() {
$('.country-list').show(300);
});
$( ".first-country").find('a').click(function(e) {
e.preventDefault();
var $this = $(this);
var text = $this.text();
$( ".first-country").find('input').attr('value', text);;
$('.first-country #country-list').hide(300);
});
That all works fine,but when I try to type something on input field (for example blabla, and then I click on dropdown for example Spain, value attribute is changed, but blabla is still written on input, and js output that as a value, not the string from value attribute.
What I am doing wrong. Here is working fiddle if it is easier to understand what I am having trouble with.
Thanks
Upvotes: 1
Views: 442
Reputation: 79
Add one line to your javascript:
$('.country-list').hide();
$( ".first-country").find('input').focus(function() {
$('.country-list').show(300);
});
$( ".first-country").find('a').click(function(e) {
e.preventDefault();
var $this = $(this);
var text = $this.text();
$( ".first-country").find('input').attr('value', text);
$( ".first-country").find('input').val(text); // <-- this one
$('.first-country #country-list').hide(300);
});
Upvotes: 1
Reputation: 42054
Your issue is in this line:
$( ".first-country").find('input').attr('value', text);;
In order to set/get the input value you need to use .val()
I would suggest to change this selector (the IDs must be unique):
.first-country #country-list
to:
#country-list
And instead of:
$( ".first-country").find('input')
you can reduce to:
$( ".first-country input")
The snippet:
$('.country-list').hide();
$( ".first-country input").focus(function() {
$('.country-list').show(300);
});
$( ".first-country").find('a').click(function(e) {
e.preventDefault();
var $this = $(this);
var text = $this.text();
$( ".first-country input").val(text);
$('#country-list').hide(300);
});
.country input {
color: #2980B9;
font-size: 18px;
line-height: 27px;
padding: .5rem .5rem;
text-transform: uppercase;
width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="country first-country col-md-3">
<input type="text" id="country1" placeholder="Select country/region" value="">
<ul id="country-list" class="country-list">
<li><a href="#">Spain</a></li>
<li><a href="#">France</a></li>
</ul>
</div>
Upvotes: 3