TheWebs
TheWebs

Reputation: 12923

How can I tunr this code into one function jquery

Consider the following snippit:

$('#num-locations input[type="checkbox"]').on('click', function(e) {
  var checkedInputs = $("#num-locations input[type=checkbox]:checked");
  var manageWrappers = $(".manage-wrapper");

  manageWrappers.removeClass("hide-on-check");
  if (!checkedInputs.length) return;

  var locations = checkedInputs.map(function() { return $(this).data("location") }).get();

  manageWrappers
    .filter(function() {
      return !locations.includes($(this).data("city"));
    }).addClass("hide-on-check");
});


$('#num-cities input[type="checkbox"]').on('click', function(e) {
  var checkedInputs = $("#num-cities input[type=checkbox]:checked");
  var manageWrappers = $(".manage-wrapper");

  manageWrappers.removeClass("hide-on-check");
  if (!checkedInputs.length) return;

  var cities = checkedInputs.map(function() { return $(this).data("city") }).get();

  manageWrappers
    .filter(function() {
      return !cities.includes($(this).data("city"));
    }).addClass("hide-on-check");
});

$('#num-provinces input[type="checkbox"]').on('click', function(e) {
  var checkedInputs = $("#num-provinces input[type=checkbox]:checked");
  var manageWrappers = $(".manage-wrapper");

  manageWrappers.removeClass("hide-on-check");
  if (!checkedInputs.length) return;

  var provinces = checkedInputs.map(function() { return $(this).data("province") }).get();

  manageWrappers
    .filter(function() {
      return !provinces.includes($(this).data("province"));
    }).addClass("hide-on-check");
});

Each one of these does exactly what I want them to do, with some glitches. For example if you check a checkbox or two or three or what ever in #num-locations and then a couple in #num-provinces your locations were re-set and unhidden.

The goal is to make this into one function that adds to an array of "checked" locations, cities or provinces and then hides manageWrappers based on what is clicked and shows those that are not clicked.

I am unsure how to watch for multiple on click events in one function, hence why I am asking here.

Any ideas?

Upvotes: 0

Views: 25

Answers (1)

fdomn-m
fdomn-m

Reputation: 28611

I am unsure how to watch for multiple on click events in one function

The .on("click"... applies to all the elements in the selector, to select multiple elements, separate them with a comma ,, the initial update to your code being:

$('#num-cities input[type="checkbox"],#num-provinces input[type="checkbox"]').on('click', function(e) {
    var checkedInputs = $(this).filter(":checked");

You will need to make other changes to become a single function, but this answers the question asked.

Upvotes: 1

Related Questions