简体   繁体   中英

More than one form on same page focus on same input where before submit

i have a problem that i have more than one forms on same page and i want to focus same input field where it has before submit the form but if i submit then focus lost from that place . i am using more forms with same fields .like for sale item sales fields item name, item price ,item quantity when i change quantity then submit that form i want that after reload page focus remain on same quantity field 在此处输入图片说明 these are two different form when i change qty of fist field then submit this form ai want that it will be focused same field after reload page please help me if any.

Try to cache the focused input field each time you click on one using the JS sessionstorage API.

var els = $('input, select');
els.each(function(i){
    $(this).on('focus', function(){
        sessionStorage.setItem('focused', i);
    })
})

Then when the page reloads, fetch the entry from the sessionstorage and give focus to the same element.

$(function(){
    var index = parseInt(sessionStorage.getItem('focused'));
    var els = $('input, select');
    $(els[index]).focus();
})

A more robust solution would be to cache a unique id (if any) of the input field instead of the indexed number. This way you could attach a single event to the body, and listen for the focus.

$('body').on('focus', 'input, select', function(e){
    sessionStorage.setItem('focused', e.target.id);
});

And then fetch the cached id on page load

$(function(){
    var id = sessionStorage.getItem('focused');
    $('#'+id).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