I'm using JavaScript and JQuery 1.8.3 to rebuild a form built by Django-filter. My purpose is to only present options that will yield a result to the user. The Django stuff all works fine and this is purely a JavaScript question. I should explain that I'm essentially a Python guy and I find JavaScript quite hard to get my head round. My working code looks like this:
<script>
$(document).ready(function() {
$('#id_scheme').focus();
$('#id_scheme').change(function() {
switch (($('#id_scheme').val())) {
{% for scheme in schemes %}
case '{{ scheme.pk }}':
$('#id_paragraph').empty();
{% for k in scheme.paragraph_set.all %}
{% if k.decision_set.all %}
$('#id_paragraph').append('<option value="{{ k.pk }}">{{ k }}</option>');
{% endif %}
{% endfor %}
break;
{% endfor %}
}
});
$('#id_paragraph').focus(function() {
switch (($('#id_scheme').val())) {
{% for scheme in schemes %}
case '{{ scheme.pk }}':
$('#id_paragraph').empty();
{% for k in scheme.paragraph_set.all %}
{% if k.decision_set.all %}
$('#id_paragraph').append('<option value="{{ k.pk }}">{{ k }}</option>');
{% endif %}
{% endfor %}
break;
{% endfor %}
}
});
});
</script>
You will see the obvious problem - I'm repeating an anonymous function. I've tried the following methods to make this a named function so I can just call it on both a change to the scheme select
and on focussing the paragraph select
but with no success.
function myCode() {
// code you see above here
}
...
$('#id_scheme').change(myCode());
and:
$.myCode = function() {
// code you see above here
}
...
$('#id_scheme').change($.myCode());
I really hate repeating code. Can anyone tell me what incantation I'm missing?
... .change(myCode)
. – Jan Dvorak May 23 '13 at 15:36