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

标签 javascript jquery forms 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;
    }
  }
});

JsFiddle

我很想得到一些帮助,因为我已经被困了这么久......提前致谢!

最佳答案

编辑:下面是对代码工作原理的描述:

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]();
});

关于javascript - jQuery 显示/隐藏所需的密码字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55269140/

相关文章:

javascript - AngularJS 搜索框指令或如何避免 Controller 中的代码重复

javascript - 使用 javascript 提交表单并将结果返回到同一页面

javascript - 为什么此正则表达式返回预期的较短版本?

javascript - 检测同一个类中的哪个元素被点击并显示div

javascript - 如何使用 JQuery 使具有特定 URL 的选项卡处于事件状态

javascript - JQuery:加载事件如何处理图像?

python - Pyramid 中的 HTML 表单名称数组解析(Python)

python - 使用 Python 登录网站,填写表格,然后退出

javascript - 模式定义中预期的替换属性

javascript - 如何在禁用 css 时隐藏 div?