简体   繁体   中英

How to auto scroll to the focused input field division using javascript or jquery while cloning the form multiple times

Auto scroll to the focused input field form division. I'm cloning the form to add more users to add at once. So it must scroll down to the input field when I click the add buttion

HTML:

 $(document).ready(function() { $('#id_i_fa_add').click(function duplicate() { $('#id_i_fa_add').off('click'); $('.fa.fa-trash').off('click'); var original = document.getElementById('id_div_add' + i); var clone = original.cloneNode(true); $('#' + clone.id + " ai").attr('class', 'fa fa-trash'); $('#' + clone.id + " ai").attr('id', 'id_i_fa_del' + i); clone.id = "id_div_add" + ++i; clone.querySelectorAll("[id = 'id_span_error_email" + (i - 1) + "']")[0].id = 'id_span_error_email' + i; $(clone).find('input').val(""); $(clone).find('span').text(""); document.getElementById('id_form_append').appendChild(clone); $('#id_form_append input').focus(); $('#id_i_fa_add').on('click', duplicate); $('.fa.fa-trash').on('click', duplicate_trash); }); }); function duplicate_trash() { var trash_id = this.id; var parent_trash_id = $('#' + trash_id).parents().eq(1).attr('id'); $('#' + parent_trash_id).remove() }
 <form id='id_form_append' action="#"> <div id='id_div_append'> <div id='id_div_add0' class="panel_box"> <div class="form_group"> <label>Email Address</label> <div class="form-group form-inline"> <div class="input-group" style="width: 100%;"> <input name="email" type="text" class="form-control" placeholder="e-mail" autofocus> <div class="input-group-addon">domains</div> </div> </div> <span id='id_span_error_email0' class='class_span0'></span> </div> <a class="action" href="#"> <i id='id_i_fa_add' class="fa fa-plus"></i> </a> </div> </div> </form>

you can scroll to a position using:

$(window).scrollTop(/* pixel count */)

to retrieve the position of any element, use:

$(/* selector */).position()

you then have a simple object containing the position of the selected element. To retrieve the pixel to the top, use:

$(/* selector */).position().top

Note: This will only work correctly if your selector selects exactly one element.

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