Skip to content Skip to sidebar Skip to footer

Handling Javascript Cookies

I'm studying Javascript cookie. Basically what I want is when the first time user input their number it will save the cookie name, value and expiration date to 365. When the use

Solution 1:

Add name to you form:

<formname="your_form_name_here">
    Enter Mobile Number: <inputtype="text"name="mobtel"value=""><br><inputtype="submit"value="Save Cookie"onclick="set_name(this.form)"></form>

Solution 2:

Here's a working version.

This is what I did: 1 - getCookie() and setCookie() weren't defined. I used the W3Schools functions to supplement them. 2 - There were some scripting errors (missing semi-colons,etc) I fixed those. 3 - for the set_name() function, I changed it to a DOM query to access the input which held the telephone number.

<script>functioncheckCookie() {
    var mob_tel=getCookie("mob_tel");
    if (mob_tel!=null && mob_tel!="") {
        alert("Welcome again " + mob_tel);
    } else {
        set_name("");
    }
}

functiongetCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
        x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
        y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
        x=x.replace(/^\s+|\s+$/g,"");
        if (x==c_name) {
            returnunescape(y);
        }
    }
}

functionsetCookie(c_name,value,exdays) {
    var exdate=newDate();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value;
}

functionset_name(form) {
    var mob_tel = document.getElementById('mobtel').value;
    if (mob_tel != "") {
        if (confirm("Are you sure you want this saved as your number?")) {
            setCookie ("mob_tel", mob_tel, 365);
            //window.history.go(0);
        }
    } elsealert("Geez, at least enter something, entering nothing will cause an error.");
}
</script><bodyonload="checkCookie()"><form>
            Enter Mobile Number: <inputtype="text"name="mobtel"id="mobtel"><br><inputtype="submit"value="Save Cookie"onclick="set_name(this.form)"></form></body>

Post a Comment for "Handling Javascript Cookies"