JSFiddle - React, Tailwind, and code Playground
HTML
<div id="addContact">
<form id="addContactForm">
<label for="username">Username:</label>
<input type="text" id="username" name="username" autofocus="autofocus" maxlength="15">
<br>
<label for="fullName">Full name:</label>
<input type="text" name="fullName" maxlength="50">
<br>
<label for="email">Email:</label>
<input type="text" name="email" maxlength="50">
<br>
</form>
<div id="addContactList"></div>
</div>
JavaScript
// This simulates the data that's returned by AJAX
var data = [{
username: "blabla",
email: "[email protected]"
}, {
username: "gege",
email: "[email protected]"
}];
addAContact();
function addAContact() {
var addContactsList = document.getElementById('addContactList');
$('#addContactForm').on('keyup change', function () {
console.log("Typing");
var self = this;
// Add a short delay to not post for every letter typed quickly
delay(function() {
var userSearchData = {};
$.each(['email', 'username', 'fullName'], function (_, el) {
var val = $(self).find('input[name="' + el + '"]').val();
if (val.length >= 3) {
userSearchData[el] = val;
}
});
if ( !isEmpty(userSearchData) ) {
var html = '';
//$.post('/post/addContact', { userSearchData: userSearchData }, function (data) {
if (data) {
$.each(data, function (index, value) {
html += '<div>' + value.username +'</div><button class="addAsFriend">Add as Friend</button>';
});
addContactsList.innerHTML = html;
} else {
addContactsList.innerHTML = '';
}
//});
} else {
addContactsList.innerHTML = '';
}
}, 225 );
});
}
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
$('#addContactList').on('click', '.addAsFriend', function (event) {
event.stopPropagation();
$(this).text('Request sent!');
$(this).prop('disabled', true);
});
var hasOwnProperty = Object.prototype.hasOwnProperty;
function isEmpty(obj) {
if (obj == null) return true;
if (obj.length > 0) return false;
if (obj.length === 0) return true;
for (var key in obj) {
if (hasOwnProperty.call(obj, key)) return false;
...