我有一个表格可以更改用户的个人详细信息。在这种形式中,我允许用户更改他们的电子邮件和/或密码。使用 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;
}
}
});
我很想得到一些帮助,因为我已经被困了这么久......提前致谢!
最佳答案
编辑:下面是对代码工作原理的描述:
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/