简体   繁体   中英

inline <script> block with focus not firing second time around when using jQuery html to populate div

I have the following JavaScript code block inside a HTML form that sets the z-index of a <div> to 0 when focus is placed on a form field.

                <script type="text/javascript">
                    $('.olabel input').focus(function() {
                        console.log('focus on a form field');
                        $('.olabel').css('zIndex', '0');
                        $(this).closest('.olabel').css('zIndex', 1998);
                    });                                 
                </script>

I have the following markup (the textbox class has no z-index attribute set on it):

<div class="field olabel d_field">
Address Line 1: <input type="text" name="address11" id="address11" size="20" class="textbox" />
/** other HTML fields in here **/
</div>

I also have the following JavaScript that executes when a radio button is clicked with a specific value. Basically, when 'No' is selected from a Yes/No radio button the code below executes.

var target = $(this).closest('.d_option_row');
// d_address_form is a string variable that contains HTML
$(target).find('.d_options_detail_d_address_container').html(d_address_form);

The problem I am finding is that when I click 'No' for the first time, the console.log('focus on a form field') writes out to the console correctly. However, if I then hide the form (by clicking 'Yes') and then show the form again (by clicking 'No') then the console does not get this entry populated into it and the z-index is not re-written by the JavaScript as it should.

Is this a problem with my using the jQuery html() method?

The markup of the form isn't changing between show/hides, so is there a reason why my inline <script> tags won't be firing second time around?

I think you need to use delegation for your event handler:

<script type="text/javascript">

    // You can use `document` or some other parent container that is always present

    $( document ).on( 'focus', '.olabel input', function() {

        console.log('focus on a form field');
        $('.olabel').css('zIndex', '0');
        $(this).closest('.olabel').css('zIndex', 1998);
    });  

</script>

http://api.jquery.com/on/

I think the problem is that you don't attach the focus event after creating the new element. try:

function eventHandler() {
    console.log('focus on a form field');
    $('.olabel').css('zIndex', '0');
    $(this).closest('.olabel').css('zIndex', 1998);
}

$(target).find('.d_options_detail_d_address_container').html(d_address_form).focus(eventHandler);

when creating the new element, does it help?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM