I am new to Jquery and learning. I wrote some script, but I know its not efficient. Trying to follow DRY principles. Can someone please make this look nicer…it works fine, but i dont like it.
It works, just not efficient code.
<script>
$(document).ready(function () {
var val = $('#id_ocftype').val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
$('#id_ocftype').change(function () {
var val = $(this).val();
if (val <= 3) {
$('#div_id_date').hide();
$('#div_id_amount').hide();
$('#div_id_signedby').hide();
}
else {
$('#div_id_date').show();
$('#div_id_amount').show();
$('#div_id_signedby').show();
};
});
});
</script>
4
Answers
you can create a common function
also you can use toggle
The elements to show or hide are always the same, so you can put them all into a single variable and reference that variable.
You can look into .toggleClass.
It allows you to specify when to add/ remove class.
Since the conditional statement inside the jquery code is same. You can wrap it into single javascript function and call it whereever it is needed.