How to create a onclick event for each search results items so that it render a product page with meta data of that item. I have successfully able to filter items as per keypress. Now I want to give a click event for filtered item to open a product page. How would I do that in Javascript? Please help me figure out this.
**My HTML code**
<!-- Search form -->
<div class="container">
<div class="active-pink-4 mb-4 mt-4">
<input class="form-control form_search" type="text" placeholder="Search" aria-label="Search" id="search">
</div>
<div id="match-list" name="matchid"></div>
</div><!-- End of Search form -->
<div class="container"><!-- Strat of login container-->
<div class="row" id="viewhide"><!-- Strat of login row-->
<div class="col-md-6 d-none d-sm-block"><!--start of col login img-->
<img src="https://img.etimg.com/thumb/width-1200,height-900,imgsize-27424,resizemode-1,msid-14351710/industry/healthcare/biotech/pharmaceuticals/free-medicines-to-all-patients-in-government-hospitals-from-november.jpg">
</div><!--End of col login img-->
<div class="col-md-6 text-center fadeIn first"><!--Start col login-->
<h2>Sign In</h2>
<!-- Login Form -->
<form>
<input type="text" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Username">
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
<div id="formFooter">
<a class="underlineHover mb-2" href="#">Forgot Password?</a>
</div>
<input type="submit" class="btn btn-primary d-flex justify-content-center d-md-table mx-auto mb-2 btn-round" value="Login">
<h5>You don't have an account ?</h5>
<input type="button" class="btn btn-primary d-flex justify-content-center d-md-table mx-auto mb-5 btn-round" value="Register">
</form>
</div><!-- End of col login-->
</div><!-- End of login row-->
</div><!-- End of login container-->
**My Js code:**
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
// Search states.json and filter it
const searchStates = async searchText =>{
const res = await fetch('lib/json/data.json').then(response =>{
//console.log(response);
if (!response.ok) {
throw Error("Error");
}
return response.json();
}).then(data =>{
//console.log(data.item);
let states = data.item;
//console.log(states, "states");
// Get matches to current text input
let matches = states.filter(state =>{
const regex = new RegExp(`^${searchText}`, `gi`);
return state.itemName.match(regex) || state.itemMfrCode.match(regex);
});
let divhide = document.getElementById('viewhide');
if(searchText.length !== 0){
divhide.style.display = "none";
}else{
divhide.style.display = "flex";
}
//Hide all results when input is empty
if (searchText.length === 0) {
matches = [];
matchList.innerHTML = '';
}
//Hide if no results are found
if (searchText !== states) {
match = [];
matchList.innerHTML = '';
}
outputHtml(matches);
}).catch(error =>{
console.log(error);
});
};
//Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
const html = matches.map(match => `
<div class="card card-body mb-1" id="medprod" name="selectid"
onclick="getproduct()">
<h4 style="cursor: pointer;">${match.itemName}</h4>
</div>
`).join('');
matchList.innerHTML = html;
}
}
search.addEventListener('input', () => searchStates(search.value));
//On clcik search result items function
function getproduct(){
}
**My Json structure**
{
"clientId": "1234",
"systemId": "2010",
"orderReferenceNo": "43442",
"responseCode": "0000",
"responseDescription": "Items successfully retrieved!",
"item": [
{
"itemMfrCode": "0001001",
"qnty": "00000000",
"itemName": "clinic shampoo",
"unitPk": "30ml",
"itemCategory": " ",
"itemType": "NT",
"schemeRange": "000",
"schemeOffeQty": "000",
"rateDiffFlag": "N",
"schemeHalfValueFlag": " ",
"schemeHalfValuePerc": null,
"ratePerUnit": 20.00
},
{},
}
I should have posted the answer long before. No problem, hope it helps someone in future.
const search = document.getElementById('search');
const matchList = document.getElementById('match-list');
const productLayout = document.getElementById('product_layout');
//Search filter
const searchStates = async searchText => {
const res = await
fetch('https://data.json').then(response => {
if (!response.ok) {
throw Error("Error");
}
return response.json();
}).then(data => {
console.log(data.item);
let states = data.item;
console.log(states, "states");
matchList.style.display = 'block';
// Get matches to current text input
let matches = states.filter(state => {
const regex = new RegExp(`^${searchText}`, `gi`);
return state.itemName.match(regex) ||
state.itemMfrCode.match(regex);
});
if (searchText.length !== 0) {
productLayout.style.display = 'none';
} else {
productLayout.style.display = 'block';
}
outputHtml(matches);
}).catch(error => {
console.log(error);
});
};
//Show results in HTML
const outputHtml = matches => {
if (matches.length > 0) {
//Meta data of clicked item
//Keep adding
//${match.itemId},${match.itemRate},${match.itemColor} to the list.
const html = matches.map(match => `
<li id="${match.itemMfrCode}">${match.itemName}</li>
`).join('');
matchList.innerHTML = html;
}
}
search.addEventListener('input', () => searchStates(search.value));
/*OnClick filtered items*/
matchList.addEventListener('click', function(e) {
var target = e.target;
while (target && target.parentNode !== matchList) {
target = target.parentNode;
if (!target) {
return;
}
}
if (e.target.tagName === 'LI') {
//Get selected product name
let liInnerText = e.target.innerText;
//Store prod name in localStorage
localStorage.setItem('liText', liInnerText);
//Insert selected item in input text field
search.value = liInnerText;
//Hide search dropdown after click event
matchList.style.display = 'none';
/*View product layout*/
productLayout.style.display = 'block';
//Get product name from localStorage
var selectedName = localStorage.getItem('liText');
//Dispaly product name in HTML page
document.getElementById('prod_name').innerHTML =
selectedName;
}
});
#match-list {
display: none;
}
#product_layout {
display: none;
}
<!-- Search form -->
<div class="container" id="search_layout">
<div class="active-pink-4 mb-2 mt-4">
<input class="form-control form_search" type="text" placeholder="Search" aria-label="Search" id="search" value="" autocomplete="off" onfocus="this.value=''">
</div>
<ul id="match-list" name="matchid"></ul>
</div>
<!-- End of Search form -->
<!--Product details-->
<div class="container-fluid" id="product_layout">
<div>
<p id="prod_name"></p>
</div>