Devmix
Devmix

Reputation: 1858

storing a cookie on IE (11)

I'm trying to store a cookie in an input field which works just fine on Chrome but doesn't work on IE-11. Can anyone tell me what I'm missing so this is cookie can also work on IE? Here's my code.

Javascript:

function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
}

function myfunction() {
    setCookie("input1", '1');
    alert(getCookie("input1"));
    document.homeForm.input1.value = getCookie("input1");
}

HTML

<form name="myform">
<input type=text name=input1 value=""/>
</form>

Upvotes: 2

Views: 4591

Answers (1)

gmfm
gmfm

Reputation: 669

@progx here are some images of this working for me on IE 11. But just to insure cross browser compatibility you should enclose your attribute values in quotes.

<input type="text" name="input1" value=""/>

vs

<input type=text name=input1 value=""/>

Below is the code as used and images of the working code. Code used:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script>
$(document).ready(function() { 
    myfunction( );
});

function setCookie(key, value) {
var expires = new Date();
expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
document.cookie = key + '=' + value + ';expires=' + expires.toUTCString();
}

function getCookie(key) {
var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
return keyValue ? keyValue[2] : null;
}

function myfunction() {
setCookie("input1", '1');
alert(getCookie("input1"));
document.myform.input1.value = getCookie("input1");
}
</script>
<style>

</style>
<body>
<form name="myform">
<input type=text name=input1 value=""/>
</form>
</body>
</html>

alert image

input image

editor image

console image

Upvotes: 2

Related Questions