Search code examples
javascriptfunctionrefactoring

How to refactor my code so it's not repeating the same thing


I have 3 different buttons on my page, and when you click on one it checks the corresponding radio button.

Currently, I have each button with its own onclick function:

onclick="radioChecked1()"
onclick="radioChecked2()"
onclick="radioChecked2()"

And then there are the functions:

function radioChecked1() {
  var package1 = document.querySelector("#package1");
  package1.setAttribute("checked", 1);
}
function radioChecked2() {
  var package2 = document.querySelector("#package2");
  package2.setAttribute("checked", 1);
}
function radioChecked3() {
  var package3 = document.querySelector("#package3");
  package3.setAttribute("checked", 1);
}

These functions are doing the same thing, the only thing that changes is the number in the id of the input it's selecting.
I'm sure there's a way to simplify this into one function instead of a separate one for each button, I don't know how to do it.


Solution

  • You can refactor this code by simplifying the function and using parameters:

    function radioChecked(id) {
        var package = document.querySelector(id);
        package.setAttribute("checked", 1);
    }
    

    Then on your buttons call the function with the corresponding id:

    onclick="radioChecked('#package1')" onclick="radioChecked('#package2')" onclick="radioChecked('#package3')"