Rimer
Rimer

Reputation: 2084

Is it possible to "refresh" or "rerun" a jQuery selector after the DOM might have changed?

I have a page that loads a complicated set of forms. In this set of forms, there are password fields. These password fields have show/hide toggle switches which, when any of them are clicked, ALL the password fields are replaced with equivalents of themselves in the DOM with their types toggled between "text" and "password" to facilitate the show/hide effect. To be clear, the original input is replaceWith()'ed a brand new input with the same attributes, including ID, but with different type attributes.

The problem is when the toggle occurs, global handles I had previously made in jQuery selectors (such as $('#password_field_id')) no longer map to the password fields.

Is there a jQuery function that you can run on a selector that will RE SELECT its original CSS selector from the current DOM?

The function that replaces the inputs is as follows:

function TogglePasswordHide()
{
    var show = false;
    if ($('#basic_pass_24').attr('type') == 'password')
    {
        show = true;
    }

    $('input.password_input').each(function()
    {
        var sDisabled = '';
        if ($(this).is(':disabled'))
        {
            sDisabled = 'disabled="disabled"';
        }

        if ( show ) // show the password
        {
            $(this).replaceWith('<input type="text" '+sDisabled+' class="password_input" id="'+$(this).attr('id')+'" value="'+$(this).val()+'">');
            show_password.text('hide');
        }
        else // hide the password
        {
            $(this).replaceWith('<input type="password" '+sDisabled+' class="password_input" id="'+$(this).attr('id')+'" value="'+$(this).val()+'">');
            show_password.text('show');
        }
    });
}

...Is there a call I can make during the .each to "reload" the jquery object after the replacement has been made so that my global handles to those same relative inputs will simply update themselves rather than having to redeclare new jQuery objects with the same selectors for each element and overwrite the original handles?

Upvotes: 4

Views: 3271

Answers (1)

Sampson
Sampson

Reputation: 268472

Use event-delegation, and listen for the events on the parent form:

$("form").on("click", ".password_input", function(event) {
    /* What to do when password input is clicked */
});

Because this event is bound to the form element, you can add and remove inputs as you wish without having to worry about losing events.

When you click, or perform some other action, on one of the password inputs, this event bubbles up to the form where it is then evaluated. If the .target matches your selector (in this example, .password_input), the callback function will be invoked and you can react to the event that took place.

Upvotes: 3

Related Questions