jQuery显示/隐藏所需的密码字段

Mat*_*ijs 6 javascript forms jquery jsfiddle

我有一个表格可以更改用户的个人详细信息。我以这种形式允许用户更改其电子邮件和/或密码。使用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;
    }
  }
});
Run Code Online (Sandbox Code Playgroud)

JsFiddle

自从我被困了很久以来,希望在此方面有所帮助...预先感谢!

dob*_*ler 3

编辑:这是代码如何工作的描述:

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
});
Run Code Online (Sandbox Code Playgroud)

如果我正确理解您的用例,以下代码应该可以完成这项工作:

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]();
});
Run Code Online (Sandbox Code Playgroud)