-3

I'm trying to improve myself by working on codes. I can understand its normal state without any problems. In the sample code below, jquery, value reading, value assignment and if-else queries are nested. I could not get the code in a meaningful readable way. Can anyone write the code below in a simple expanded readable format?

$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
  var inputSpan = $(this).parent().find('span').text();
  $(this).val() != inputSpan && '' != $(this).val() && $(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive'),
  '' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active')
});

$('.input-required input, .input-required select, .input-required textarea').on('focusout', function () {
  $(this).parent().find('span').text();
  '' === $(this).val() && $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active'),
  $(this).parent().find('span').addClass('input-style-1-inactive')
});

The extended version of the first code block is correct as below?

$('.input-required input, .input-required select, .input-required textarea').on('focusin keyup', function () {
  var inputSpan = $(this).parent().find('span').text();
  if(($(this).val() != inputSpan) && ('' != $(this).val())){
    $(this).parent().find('span').addClass('input-style-1-active').removeClass('input-style-1-inactive');
  }else{
    $(this).parent().find('span').removeClass('input-style-1-inactive input-style-1-active');
  }
});
NovaYear
  • 167
  • 1
  • 2
  • 13
  • 1
    Whoever wrote that did not write it with maintenance in mind. Is it generated code by some tool? – mplungjan Feb 19 '21 at 14:19
  • Agree with mplugjan - that is terrible code to learn with. But if you must, it is quite common to place chained function calls on their own lines to make it somewhat more readable. So something like this: `$(this).parent().find('span').addClass(...).removeClass(...)` would have line breaks just before each `.`. That will make this terrible code slightly easier to comprehend. – Randy Casburn Feb 19 '21 at 14:23
  • @mplungjan, yes auto generated by a tool, maybe like https://jscompress.com – NovaYear Feb 19 '21 at 14:30

1 Answers1

1

Whoever wrote that did not write it with maintenance in mind. Is it generated code by some tool?

I would think it could be condensed to

$(':input.input-required').on('input focusout', function (e) {
  let $inputSpan = $(this).parent().find('span'), 
      text = $inputSpan.text(), 
      val = $(this).val();

  if (val && val != text) {
    $inputSpan
      .addClass('input-style-1-active')
      .removeClass('input-style-1-inactive')
  }
  else { 
   $inputSpan
     .removeClass('input-style-1-active')
     .addClass('input-style-1-inactive')
  }
});

Which may be even more readable with toggleClass

mplungjan
  • 169,008
  • 28
  • 173
  • 236