简体   繁体   中英

How to make localstorage of focus in textbox using Jquery dynamic?

 <input id="input1" type="text" />
 <br />
 <input id="input2" type="text" />

I have followed this simple script that stores the focus on the input text.

      $(document).ready(function() {
        changeFocus();
        $("#input1").click(function(){
        localStorage.setItem('txtObjectid', "input1");
        changeFocus();
        return false;
       });

      $("#input2").click(function(){
        localStorage.setItem('txtObjectid', "input2");
        changeFocus();
        return false;
       });
       });

 function changeFocus(){
   if(localStorage.getItem('txtObjectid')==null)
       id="input1"
       else
           id=localStorage.getItem('txtObjectid');
   var v = "#" + id;
   $(v).focus();
}

What I want to learn/know about is how to make the script flexible? How could I make this so that it won't search of the id = "input1" instead it will search for input[type=text]?

Something like this should do it

$(document).ready(function () {
    var id = 'input1';
    if (localStorage.getItem('txtObjectid')) {
        id = localStorage.getItem('txtObjectid');
    }

    $('#' + id).focus();

    $('input[type="text"]').on('focus', function () {
        localStorage.setItem('txtObjectid', this.id);
    });
});

FIDDLE

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