I need help writing search input to check if a content exists or not in json file.
If exists show me a pop-up "alert" that says "exists" or a pop-up "alert" says not exists.
Example
HTML
<div class="search-bar">
<input type="text" id="seeker">
</div>
<div id="content"></div>
JavaScript
var data = [
{
"id":198,
"name":"Aaron Garo",
},
{
"id":345,
"name":"Michael Stines",
},
{
"id":545,
"name":"Ully Heiz",
},
{
"id":678,
"name":"Asgaf Torino",
}
]
output = "";
$.each(data, function(key, val){
output += "<div class='values'>";
output += '<h5 class="value-id">' + val.id + '</h5>';
output += '<p class="value-name">' + val.name + '</p>'
output += "</div>";
});
$('#content').html(output);
/* SEEKER FUNCTION */
if (!RegExp.escape) {
RegExp.escape = function (s) {
return s.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, "\\$&")
};
}
jQuery(function(){
var $rows = $('.values');
$('#seeker').keyup(function () {
var regex = new RegExp(RegExp.escape($.trim(this.value).replace(/\s+/g, ' ')), 'i')
$rows.hide().filter(function () {
var text = $(this).children(".value-name").text().replace(/\s+/g, ' ');
return regex.test(text)
}).show();
});
});
Consider the following example: https://jsfiddle.net/Twisty/ocbs9e8a/
JavaScript
jQuery(function($) {
var data = [{
"id": 198,
"name": "Aaron Garo",
},
{
"id": 345,
"name": "Michael Stines",
},
{
"id": 545,
"name": "Ully Heiz",
},
{
"id": 678,
"name": "Asgaf Torino",
}
];
$.each(data, function(key, val) {
var row = $("<div>", {
class: "values"
}).appendTo($('#content'));
$("<h5>", {
class: "value-id"
}).html(val.id).appendTo(row);
$("<p>", {
class: "value-name"
}).html(val.name).appendTo(row);
});
var $rows = $('.values');
$('#seeker').keyup(function() {
var term = $(this).val();
// Showe all Rowa
$rows.show();
// Iterate each row
$rows.each(function(i, el) {
// Hide those that do not contain Term
if ($(".value-id", el).text().indexOf(term) == -1) {
$(el).hide();
}
})
});
});
This is just one way to filter the items on display. For example, if the User enters 4, only two results are shown.