I have this below code. I can display the list of JSON file but I can't click the items of the list. Could you teach me How to add click and store item function. What I would like to do is click the item of the list .After click it "NAME" value store the textbox. so then After set the value Click submit buttom then pass the NAME and related data. For example. Fist data https://api.myjson.com/bins/8x0ag
Fist data name is orange. When user click the orange. and press submit button I would like to send the code "102" and location "N34" data to Next page.
name "orange"
code "102"
location "N34"
Actually I had another code. To select item and store the value into the text field. but I changed the code after that I lost selecting function.
$(document).ready(function() {
Main.init();
});
var Main = (function($) {
return {
vars: { },
init: function() {
Main.build();
Main.events();
},
events: function() {
$(document).on('keyup', '.search', function() {
const ref = $(this).attr('data-ref');
const {
vars
} = Main;
$(`.resultUl[data-ref="${ref}"]`).html('');
const searchField = $(this).val();
const expression = new RegExp(searchField, "i");
$.each(vars.JSONdata, (key, value) => {
const {
name,
location,
code,
image
} = value;
if (name.search(expression) != -1 || location.search(expression) != -1) {
$(`.resultUl[data-ref="${ref}"]`).append(
`<li class="list-group-item link-class"
data-name="${name}"
data-code="${code}"
data-location="${location}">
<img src="${image}" height="40" width="40" class="img-thumbnail" />
${name}
<span class="text-muted">${location}</span>
</li>`
);
}
});
});
},
build: async function() {
JSONdata = await this.getJson();
this.vars = {
JSONdata
};
this.generateFields(20);
},
getJson: () => new Promise((resolve, reject) => {
$.getJSON('https://api.myjson.com/bins/8x0ag', (data) => {
resolve(data);
}).fail(function() {
reject([]);
})
}),
generateFields: (fieldNumber) => {
Array(fieldNumber).fill().map((v, i) => {
const ref = i + 1;
$('#container').append(
`<div class="fieldContainer">
<div class="btn-group">
<input type="text" class="search" data-ref="${ref}" placeholder="" class="form-control" size="3000" onkeypress="return event.keyCode!=13" />
<span class="searchclear glyphicon glyphicon-remove-circle"></span>
</div>
<ul class="list-group resultUl" data-ref="${ref}"></ul>
</div>`
)
});
},
}
})($);
I tried to add this code to above but it doesn't work.
$('#result').on('click', 'li', function() {
var name = $(this).data('name' );
var code = $(this).data('code' );
var location = $(this).data('location' );
var click_text = $(this).text().split('|');
$('#search').val($.trim(click_text[0]));
$("#result").html('');
$('#result').after('<input type="hidden" name="name" value="'+name+'">');
$('#result').after('<input type="hidden" name="code" value="'+code+'">');
$('#result').after('<input type="hidden" name="location" value="'+location+'">');
});