samedi 3 avril 2021

Change if else to switch case statement

I have a function with some if…else like this:

function updateInputs(data) {
  from = data.from;
  to = data.to;
  rangeInput = $(data.input);
  
  if (rangeInput.hasClass('rangeSalary')) {
    $inputFromSalary.prop("value", from);
    $inputToSalary.prop("value", to);      
  } else if (rangeInput.hasClass('rangeAge')) {
    $inputFromAge.prop("value", from);
    $inputToAge.prop("value", to);
  }
  
  table.draw();
}

But I need to add more statements, so I think it is better to use switch…case, so I tried to do this:

function updateInputs(data) {
  from = data.from;
  to = data.to;
  rangeInput = $(data.input).hasClass('rangeSalary');

  switch (rangeInput) {
    case 'rangeSalary':
      $inputFromSalary.prop("value", from);
      $inputToSalary.prop("value", to);
      break;
    case 'rangeAge':
      $inputFromAge.prop("value", from);
      $inputToAge.prop("value", to);
      break;
  }

  table.draw();
}

But it didn't work. What am I missing?

Aucun commentaire:

Enregistrer un commentaire