NewJSON
by sabbin
HTML
<html>
<head>
<title>ライブサーチ リアルタイム検索 01/12/2019 JQuery Search HTML Table Data by using JQuery</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:900px;">
<h2 align="center"></h2>
<h3 align="center"></h3>
<br /><br />
<div align="center">
<div id="container">
</div>
<br />
<form action="recive.php" method="post" id="submitForm">
<input type="submit" id="submit" />
</form>
</div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</body>
</html>
CSS
.fieldContainer {
margin-bottom: 16px;
}
#result {
position: absolute;
width: 100%;
max-width: 870px;
cursor: pointer;
overflow-y: auto;
max-height: 400px;
box-sizing: border-box;
z-index: 1001;
}
.list-item {
text-align: left;
}
.search {
width: 870px;
}
.link-class:hover {
background-color: #f1f1f1;
}
.btn-group {
width: 900px;
}
JavaScript
$(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 list-item"
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>
`
);
}
});
}),
$(document).on('click', '.list-item', function() {
const ul = $(this).closest('ul');
const ref = $(ul).attr('data-ref');
const name = $(this).attr('data-name');
const location = $(this).attr('data-location');
const code = $(this).attr('data-code');
const hiddenInput = $(`.hiddenField[data-ref=${ref}]`);
$(`.search[data-ref=${ref}]`).val(name).prop('disabled', true);
if (hiddenInput.length) {
$(hiddenInput).val(`${name}_${location}_${code}`);
} else {
$('#submitForm').append(
`<input
type="hidden"
class="hiddenField"
...