简体   繁体   中英

Setting Focus on dynamically created input field without knowing its ID

I have a jQuery/AJAX function that loads HTML form elements from the server. The fields on the form vary. I'd like to set focus to the 1st available input field after the load has completed. I tried:

 $(':input:enabled:visible:first').focus();

but this doesn't work :( I'm not sure how I can address the input field in jQuery. I do not know the ID of the element returned.

My function looks like the below whereas the my_html variable contains a number of simple input fields, eg

 <input type='text' name='test' value='prefilled' />

AJAX Function:

    $.loadIDX = function (idx, position){

        var url = 'URL HERE';

        $.ajax({
              url:  url, 
              type: "POST",
              data: {

                     idx:idx,
                     position:position

              },
              dataType: 'json', 
              success: function(data) {

                if(data.status=='request'){

                     var my_html = '<div id="slide_in"><div id="please_enter_'+idx+'" class="please_enter">Please enter:</div><form id="cform_'+idx+'">';

                     // loop through json & create html input form fields
                     $.each(data, function(key, val) {
                         if(key!='status'){
                            my_html += val;
                        }
                     })

                     // close up the form
                     my_html += '<input class="submit_button" type="button" value="ok" onClick="postForm('+idx+','+position+')" /></form></div>';

                    // place the new HTML into the DIV
                    $('#yn_'+idx).html( my_html );

                    // set focus... HOW?
                    $(':input:enabled:visible:first').focus();

                } else {
                    $.closeIDX(idx);
                }
              }

              });
    }

怎么样

$('#yn_'+idx).html( my_html ).find('input:first').focus();

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