I'm working on a project which contains a search form which looks like this:
Here is the HTML (actually, a Django template):
<form action="{% url action %}" method="get" class="left search col s6 hide-on-small-and-down" novalidate>
<div class="input-field">
<input id="search" placeholder="{{ placeholder }}"
autocomplete="off" type="search" name="q"
value="{{ search_form.q.value.strip|default:'' }}"
data-query="{{ search_form.q.value.strip|default:'' }}">
<label for="search" class="active"><i class="material-icons search-icon">search</i></label>
<i data-behavior="search-clear"
class="material-icons search-icon"
{% if not search_form.q.value %}style="display: none;"{% endif %}>close</i>
</div>
</form>
Here is the concomitant jQuery code:
$(document).on('click', '[data-behavior="search-clear"]', function(e) {
$('#search').val('').parents('form').submit();
});
$(function() {
setSearchClearVisibility($('#search'));
});
$(document).on('keydown', '#search', function(e) {
var $el = $(this);
setTimeout(function() {
setSearchClearVisibility($el);
}, 10);
});
function setSearchClearVisibility(el) {
if (el.val() === '') {
$('[data-behavior="search-clear"]').hide();
} else {
$('[data-behavior="search-clear"]').show();
}
}
$(document).on('keydown', '#search', function(e) {
var $el = $(this);
setTimeout(function() {
if (e.keyCode !== 27) return;
$('#search').val('').blur();
setSearchClearVisibility($el);
if ($el.data('query') !== '') {
$('#search').parents('form').submit();
}
}, 10);
});
I have a couple of questions about the jQuery code:
Firstly, it seems like the setSearchClearVisibility()
function could be refactored as follows:
function setSearchClearVisibility(el) {
if (el.val() === '') {
$('[data-behavior="search-clear"]').toggle();
}
}
Is this indeed equivalent?
Secondly, it would also seem that the line
$(document).on('keydown', '#search', function(e) {
could be replaced by
$('#search').keydown(function(e) {
or not?
Thirdly, I'm not sure why there is a 10-ms setTimeout
in a couple of places. Why not perform the action immediately?
Fourthly, I'm puzzled by the line
if (e.keyCode !== 27) return;
The key code 27
corresponds to the Escape key; would this not mean that if the key pressed is not the Escape key, the function would return
and the code below it (the toggling of the close icon visibility and submission of the form) would not be executed? I also don't notice any difference in behavior if I comment out this line.