1

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);

});
  • How often do you want to retrieve the value of ``? You can use `keyup()`, `change()`, etc. Your current script is logging the value after waiting 3 seconds. –  Jun 08 '19 at 05:58
  • I want to add a class to the input box if the user has saved the values in browser. I am trying above code which is working fine in console, but not in code. – MAHESH KUMAR Jun 08 '19 at 06:09
  • @MAHESHKUMAR I do not see where you're writing this value to localStorage or a Cookie. What event should trigger the save/update of the value? `change`, `keyup`, `blur`? – Twisty Jun 08 '19 at 07:55
  • @MAHESHKUMAR did you get this addressed? – Twisty Jun 14 '19 at 06:07

1 Answers1

0

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.

Twisty
  • 30,304
  • 2
  • 26
  • 45