Search code examples
javascriptjqueryformsjsfiddle

jQuery to show/hide required password field


I have a form to change the personal details of the user. In this form I allow the user to change their email and/or password. With jQuery I want to show a 'Current Password' field when it detects that one of these fields is changed.

For the email field this means that when it is changed the password field appears, but when the email is re-entered correctly it hides itself again.

For the password field this means it simply shows when anything is typed inside the field.

I got the basics working, but I can't get them to work with each other. So when I change both and change one back, the Current Password field hides itself.

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

Would love some help with this since I've been stuck for so long... Thanks in advance!


Solution

  • EDIT: Here's a description of how the code works:

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

    If I understood your use case correctly the following code should do the job:

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