1

First, a little disclaimer: I'm no master at working with javaScript / jQuery, although I have handled it quite a few times. Recently, I have sometimes found myself being forced to make redundant code, i.e. repeat line(s) of code regarding diferent events, because I don't know how to do it in a more efficient way. A small example would be enabling a button after checking if any checkbox in a page is selected. This is done either upon page loading or after any checkbox is selected:

var checkboxes = $("input[type='checkbox']");

$('#nextfl').attr("disabled", !checkboxes.is(":checked"));

checkboxes.click(function()
{
    $('#nextfl').attr("disabled", !checkboxes.is(":checked"));
});

I don't think this could be solved using the bind or on functions, for instance, since it refers to events not related to the same element. I believe it must exist a straightforward solution to this though, but as I said before, I have little experience in JS / jQ, and there are some similar situations where I have repeated dozens of lines of code, which is of course at least a bad practice.

0

2 Answers 2

1

You can always split redundant code into functions with javascript:

function doCheckboxLogic () {
    $('#nextfl').attr("disabled", !checkboxes.is(":checked"));
    // and any other logic that needs to be done
}

You then call that function in place of the redundant code block:

checkboxes.click(function()
{
    doCheckboxLogic();
});

There's not much gained here since it's one line of code anyway, but this really helps with encapsulating more complicated blocks of logic

Sign up to request clarification or add additional context in comments.

Comments

1

Best practice in this case is to extract common logic to its own function which can be called as required. Try this:

$(function() {
    var $checkboxes = $("input[type='checkbox']");

    function checkState() {
        $('#nextfl').attr("disabled", !$checkboxes.is(":checked"));
    }

    $checkboxes.click(checkState); // run the function on click of a checkbox
    checkState(); // run it on load of the page
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.