简体   繁体   中英

Set cookie and display in new page

function form()
{
var formVal1=document.forms ["form1"]["num1"].value;
var formVal2=document.forms ["form1"]["num2"].value;



if ( formVal1<1 || formVal1>100)
 {
  alert("Please enter a value between 1-100");
  document.form1.num1.focus() ;
  return false;
 }  
else if ( formVal2<1 || formVal2>100)
 {
  alert("Please enter a value between 1-100");
  document.form1.num2.focus() ;
  return false;
 }


 var sum= ((document.forms ["form1"]["num1"].value - 0 ) + (document.forms ["form1"]["num2"].value - 0));
      alert("Sum of two numbers:"      +sum);
if(sum>0)
{ 
var fromVal3=prompt("Please enter the third value:");
if(fromVal3<1 || fromVal3>5)
{
 alert("Please enter a value between 1-5");
 document.form1.num3.focus() ;
 return false; 
} 

var Mul=fromVal3*sum;
alert("Multiplied Value:" +Mul);

}

if(typeof(Storage)!=="undefined")
    {
    document.cookie=Mul;
    alert(document.cookie);
    var allcookies=document.cookie;
    document.write(allcookies);
    }
   else
    {
     document.getElementById("result").innerHTML="Sorry, your browser does not support web storage...";
    }


}

it is a javascipt form hmtl page to take two inputs and prompts for the third and it will multiply with sum of first two numbers and sets the result as cookie and must display the cookie on new page. can anyone help me with setting a cookie and displaying it on new page??

To set javascript cookie you need something like this

document.cookie="username=John";

or

document.cookie="username=Joh"; expires=...; path=...";

So, in your example, it would be something like:

document.cookie='Mul='+Mul;

As far as getting cookies goes, all you have is document.cookie which will look something like a=b; c=d; e=f a=b; c=d; e=f a=b; c=d; e=f which means that you need to split few times to get what you need. Something like this:

var c = document.cookie.split('; ');
for (i=0;i<c.length;i++) {
  var cookie = c[i].split('=');
  if (cookie[0]=='Mul') {
    var myCookie = cookie[1];
    break;
  }
}

After this, you will have your cookie stored in myCookie variable.

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