I have some JSON data that I’m searching through with jQuery.grep(). Basically, I have some search boxes, and want to return only the JSON records that match what’s entered in the boxes.
Here, have some code:
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var events =
[{
'id': '1',
'title': 'Test event',
'start': '2012-08-08 18:45:00',
'end': '2012-08-15 18:45:00',
'participant': 'yes',
'notes': 'A small river named Duden flows by their place and supplies it with the necessary regelialia.',
},
{
'id': '2',
'title': 'Another test event',
'start': '2012-08-24 16:37:00',
'end': '2012-08-26 16:37:00',
'participant': 'yes',
'notes': 'It is a paradisematic country, in which roasted parts of sentences fly into your mouth. Even the all-powerful Pointing has no control about the blind texts it is an almost unorthographic life.',
},
{
'id': '3',
'title': 'infinity event',
'start': '2012-08-09 22:44:00',
'end': '2012-08-09 15:44:00',
'participant': 'no',
'notes': 'Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts.',
}];
$('#output').html(JSON.stringify(events));
$('#title_search').change(function() {
var sorted_events = events;
sorted_events = $.grep(events, function(evt,i){
return evt.title.toLowerCase().indexOf($('#title_search').val()) >= 0
});
$('#output').html(JSON.stringify(sorted_events));
});
});
</script>
</head>
<body>
Title: <input type='text' id='title_search'></input><br/>
Notes: <input type='text' id='notes_search'></input><br/>
Q: <input type='text' id='q_search'></input><br/>
<div id="output">
</div>
</body>
As you can see, when #title_search changes, it greps all ‘Title’ fields in the JSON and only returns those that match. This is all working fine.
Now, I want to do the same for the ‘Notes’ field (and other text fields that aren’t in this example), but it seems inefficient (and just plain wrong) to write the same function over and over for each search field. That’s where my JavaScript skills break down. I know this is possible in JavaScript/jQuery, but just never quite grasped it. Could someone show me how, and explain it to me like I’m five?
Bonus points: I’d like to also add a dropdown, since there are only two possible values for ‘participant’, and have it work the same way as the text fields.
I think this is what you actually expecting, added support for dropdown selection also
Look at the fiddle demo
Html
Javascript