I'm using an rfid scanner to input two items into the form, RIN and RFID, one after the other. The scanner outputs a string and enter. I want to autofocus onto the first entry of the form and then the second. The enter press on the first does not change the page since it can't submit unless both fields are filled. How do I start the page focus on the first and jump focus to the second? Is there a better solution?
views.py
def take(request):
if request.method == "POST":
form = TakeForm(request.POST)
if form.is_valid():
take = form.save(commit=False)
take.TA = request.user
take.Timestamp = timezone.now()
tool = Tool.objects.get(RFID=take.RFID.RFID)
if tool.Out == False:
tool.Out = True
take.In_or_Out = 'Out'
tool.Out_with = take.RIN
tool.Times_used += 1
tool.Last_taken_out = timezone.now()
tool.save()
take.save()
else:
tool.Out = False
take.In_or_Out = 'In'
tool.Out_with = None
tool.Last_taken_in = timezone.now()
tool.Net_time_out += tool.Last_taken_in - tool.Last_taken_out
tool.save()
take.save()
return redirect('take')
else:
form = TakeForm()
return render(request, 'info/take.html', {'form': form})
forms.py
class TakeForm(forms.ModelForm):
class Meta:
model = Take
fields = ('RFID','RIN')
take.html
{% extends "info/header.html" %}
{% load staticfiles%}
{% block content %}
<script type="text/javascript">
window.onload = function() {
document.getElementById("id_RFID").focus();
};
$(document).on('keydown', ':focusable', function (e) {
if (e.which == 13) {
e.preventDefault();
// Get all focusable elements on the page
var $canfocus = $(':focusable');
var index = $canfocus.index(this) + 1;
if (index >= $canfocus.length) index = 0;
$canfocus.eq(index).focus();
}
});
<h1>Take In or Out</h1>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
{% endblock %}