Reputation: 41
I have a two input text fields. I need to pass the value from the dynamic list items when a user clicks it respectively.
User story: When a user selects first input text field and clicks the list item, It should pass value from the selected list item to first input text field. and When a user selects second input text field and clicks the list item, It should pass value from the selected list item to second input field.
Here is my code: https://jsfiddle.net/shekhar123/uork6yhu/24/
<form action="/users" method="post">
<div>
<input type="text" id="firstInputField" palceholder="select the listitem" />
<input type="text" id="secondtInputField" palceholder="select the list item" />
</div>
<h3>dynamic list item</h3>
<div>
<ul class="list-group text-center" id="ulItem"></ul>
</div>
//Jquery file
var listItem = [{
name: "name1"
}, {
name: "name2"
}, {
name: "name3"
}];
$(document).ready(function() {
for (var prop in listItem) {
$("#ulItem").append('<li class="list-group-item list-group-item-action">' + listItem[prop].name + '</li>');
}
});
I will be very thankful for your help and suggestion.
Upvotes: 1
Views: 2240
Reputation: 8743
The key is to set the a variable when one of the text fields gets the focus. The rest doesn't change. DEMO
HTML:
<input id="input1" class="fields">
<input id="input2" class="fields">
<ul id="mylist">
<li>1st value</li>
<li>2nd value</li>
<li>3rd value</li>
<li>4th value</li>
</ul>
JS:
let selectedField = null;
$(".fields").on("focus", function() {selectedField = $(document.activeElement);});
$("#mylist li").on("click", function() {
if (selectedField != null)
selectedField.val($(this).html());
});
This is somewhat limited, especially if there are other inputs visible for which you then should reset the variable again when they get the focus. I personally would prefer dropdowns AKA comboboxes.
Upvotes: 1