JQuery, чтобы показать / скрыть обязательное поле пароля - PullRequest
6 голосов
/ 20 марта 2019

У меня есть форма для изменения личных данных пользователя.В этой форме я разрешаю пользователю менять свою электронную почту и / или пароль.С помощью jQuery я хочу показать поле «Текущий пароль», когда оно обнаружит, что одно из этих полей изменено.

Для поля электронной почты это означает, что при его изменении поле пароля появляется, но когда электронная почтаповторно введенный правильно, он снова скрывается.

Для поля пароля это означает, что он просто показывает, когда что-то набрано внутри поля.

Я получил основы работы, но не могу получитьим работать друг с другом.Поэтому, когда я изменяю оба и меняю один обратно, поле «Текущий пароль» скрывается.

let requiredSet;

$('.js-show-target-on-change').on('input', function() {
  const target = $('.js-show-target-on-change__target');
  let currentValue = $(this).val();

  if ( $(this).data('type') === 'email' ) {
    const emailValue = $(this).data('value');

    if ( currentValue !== emailValue && !requiredSet === true ) {
      target.show();
      target.find('input').prop('required', true);

      requiredSet = true;
    } else if ( currentValue === emailValue ) {
      target.hide();
      target.find('input').prop('required', false);

      requiredSet = false;
    }
  } else {
    if ( !requiredSet === true ) {
      target.show();
      target.find('input').prop('required', true);

      requiredSet = true;
    } else if ( !currentValue.length ) {
      target.hide();
      target.find('input').prop('required', false);

      requiredSet = false;
    }
  }
});

JsFiddle

Буду рад некоторой помощи с этим, так как я былзастрял так долго ... Заранее спасибо!

Ответы [ 2 ]

3 голосов
/ 20 марта 2019

РЕДАКТИРОВАТЬ : Вот описание того, как работает код:

cost email = $('#email').val() // get the starting value of the email 
                               // field to check if it has changed
$('.js-show-target-on-change').on('input', function(){

    const f = $('#email').val() !== email 
        // check if the old email value is different than the new email value

        || $('#newPassword').val().length > 0 
        // check if there is text in the new password field

        ? 'show' : 'hide'; 
        // if one of the above statements are true,show the field, else hide it

    $('.js-show-target-on-change__target')[f](); 
    // update the field based on the above condition
});

Если я правильно понял ваш сценарий использования, следующий код должен выполнить работу:

const email = $('#email').val();
$('.js-show-target-on-change').on('input', function() {
  const f = $('#email').val() !== email || $('#newPassword').val().length > 0 ? 'show' : 'hide';
  $('.js-show-target-on-change__target')[f]();
});
1 голос
/ 20 марта 2019

Используйте атрибут, чтобы указать, что входное значение было изменено, а затем используйте этот атрибут, чтобы переключать видимость элемента ввода.

$('.js-show-target-on-change').on('input', function() {
  const target = $('.js-show-target-on-change__target');
  let currentValue = this.value;

  // if input is email
  if (this.id === 'email') {
    // get default value
    let defValue = $(this).data('value');
    // set attribute value based on old and default value
    $(this).attr('data-changed', defValue !== currentValue);
  } else {
    // if password field then set attribute based on length
    $(this).attr('data-changed', currentValue.length > 0);
  }

  // check number of changed fields 
  let visible = $('input[data-changed="true"]').length > 0;

  // toggle based on the value
  target.toggle(visible);
  target.find('input').prop('required', visible);

});

$('.js-show-target-on-change').on('input', function() {
  const target = $('.js-show-target-on-change__target');
  let currentValue = this.value;

  // if input is email
  if (this.id === 'email') {
    // get default value
    let defValue = $(this).data('value');
    // set attribute value based on old and default value
    $(this).attr('data-changed', defValue !== currentValue);
  } else {
    // if password field then set attribute based on length
    $(this).attr('data-changed', currentValue.length > 0);
  }

  // check number of changed fields 
  let visible = $('input[data-changed="true"]').length > 0;

  // toggle based on the value
  target.toggle(visible);
  target.find('input').prop('required', visible);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" accept-charset="UTF-8" enctype="multipart/form-data" class="c-form">
  <div class="c-form__row">
    <label class="c-form__label" for="email">Email</label>
    <div class="c-form__field">
      <div class="c-input__control">
        <input required class="c-input js-show-target-on-change" data-type="email" type="email" id="email" name="email" value="info@johndoe.com" data-value="info@johndoe.com">
      </div>
    </div>
  </div>

  <div class="c-form__row">
    <label class="c-form__label" for="newPassword">New password</label>
    <div class="c-form__field">
      <div class="c-input__control">
        <input class="c-input js-show-target-on-change" type="password" id="newPassword" name="newPassword">
      </div>
    </div>
  </div>

  <div class="c-form__row js-show-target-on-change__target" style="display: none;">
    <label class="c-form__label" for="currentPassword">
      Current password
      <span class="u-warning">(required to change email or password)</span>
    </label>
    <div class="c-form__field">
      <div class="c-input__control">
        <input class="c-input" type="password" id="currentPassword" name="password">
      </div>
    </div>
  </div>

  <div class="c-form__submit">
    <button class="c-button c-button--fullwidth" type="submit">Save</button>
  </div>
</form>
...