Create a gist now

Instantly share code, notes, and snippets.

A barcode book scanner with an export to CSV file
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<script src="http://momentjs.com/downloads/moment.min.js"></script>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet">
<script>
$(function() {
$('#books').on('click', 'button', function(e) {
e.preventDefault();
$(this).parents('tr').remove();
});
$('#download').on('click', function(e) {
var csv = '';
e.preventDefault();
$('#books > tr').each(function(index, row) {
csv += $('button', row).data('isbn')+'\t'+$('input', row).val()+'\t'+$('.date', row).data('date')+'\n';
});
var blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
var link = document.createElement("a");
var url = URL.createObjectURL(blob);
link.setAttribute("href", url);
link.setAttribute("download", 'books.csv');
link.style = "visibility:hidden";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
});
$('input[name=ISBN]').on('change', function() {
var input = $(this),
isbn = input.val().replace(/\D/g,''),
title = function(item) {
return item.volumeInfo.title.replace(/'/g, "&#39;");
};
if(isbn.length > 0) {
$.getJSON("https://www.googleapis.com/books/v1/volumes?q="+isbn, function (response) {
var item, i, row, list, now = moment();
input.val('');
if(!response.items || response.items.length === 0) {
response.items = [{volumeInfo: {title: ""}}];
}
item = response.items[0];
row = "<tr>"
+ "<th><button type='button' class='close' data-dismiss='alert' aria-label='Close' data-isbn='"+isbn+"'><span aria-hidden='true'>&times;</span></button></th>"
+ "<td><code>"+isbn+"</code></td>"
+ "<td><input name='Title' value='"+title(item)+"' list='isbn_"+isbn+"' class='form-control'></td>"
+ "<td class='date' data-date='"+now.format()+"'>"+now.format('MMM-DD-YYYY, h:mm:ss a')+"</td>"
+"</tr>";
if($('#isbn_'+isbn).length === 0) {
list = "<datalist id='isbn_"+isbn+"'>";
for (i = 0; i < response.items.length; i++) {
item = response.items[i];
list += "<option value='"+title(item)+"' />";
}
list+= "</datalist>";
$('body').append(list);
}
$('#books').prepend(row);
});
}
})
});
</script>
</head>
<body>
<input type="text" name="ISBN" placeholder="Scan barcode"/>
<button class='btn btn-info' id='download'><span class='glyphicon glyphicon-save'></span></button>
<table class='table'>
<thead>
<tr>
<th></th>
<th>ISBN</th>
<th>Title</th>
<th>Date</th>
</tr>
</thead>
<tbody id='books'></tbody>
</table>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment