Get saved value from browsers

浪尽此生 提交于 2020-04-11 11:55:13

问题


How to get saved value from browsers in jquery,Im Using this script.

require(['jquery', 'jquery/jquery.cookie', 'jquery/ui'], function($){

    setTimeout(function(){
      console.log($('input#email').val());

        var subjectLength = $('#email').val().length;
        if(subjectLength > 0) {
            console.log('Value Available');
        } else {
            console.log('Value not  Available');
        }


    }, 3000);

});

回答1:


It looks like you are trying to write to or update a cookie via JavaScript in Magento. You could also do this with PHP using Session or Cookies too. Since you said 'from browser' I am assuming you want a JavaScript solution.

Basically, you will have a Setter and Getter function to set the name, value, and expiration of a cookie and then a function to get the value from a specifically named cookie. Sometimes you might have a clear or delete function too that basically sets he cookie to expire in the past.

I found the following which will help you: https://magento.stackexchange.com/questions/163345/magento-2-how-to-use-cookie

require(['jquery', 'jquery/jquery.cookie', 'jquery/ui'], function($){
  setTimeout(function(){
    console.log($('input#email').val());
    var subject = $('#email').val();
    var date = new Date();
    var minutes = 60;
    date.setTime(date.getTime() + (minutes * 60 * 1000));
    if($.cookie('subject').length) {
      console.log('Updating Cookie Value: "subject", "' + subject + '"');  
      $.cookie('subject', subject, {path: '/', expires: date});
    } else {
      console.log('Setting Cookie Value: "subject", "' + subject + '"');  
      $.cookie('subject', subject, {path: '/', expires: date});
    }
  }, 3000);
});

You can expand on this with your own functions if you plan to do it a lot.

function setCookie(k, v, e){
  var check_cookie = $.cookie(k); // Get Cookie Value
  var date = new Date();
  var minutes = e || 60;
  date.setTime(date.getTime() + (minutes * 60 * 1000));
  if(check_cookie.length){
    $.cookie(k, '', {path: '/', expires: -1});
  }
  $.cookie(k, v, {path: '/', expires: date});
}

function getCookie(k){
  return $.cookie(k);
}

function deleteCookie(k){
  $.cookie(k, '', {path: '/', expires: -1});
}

Hope that helps.



来源:https://stackoverflow.com/questions/56503795/get-saved-value-from-browsers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!