I'm relatively new to JavaScript and I am working on a new application. Based on the results of four drop-down selections, I would like to calculate and display a text box announcing the result. The code below allows me to make my selections on the html form and press the "submit" button, but no results are returned.
I'm having a hard time debugging because I don't understand how to get periodic output on screen (document.write doesn't seem to work) to interpret program flow. I'm not even sure if the js is running...do I somehow need to call my js from within the HTML? Do I need to store my js in an external file and call that external file?
Thanks!
<html>
<head>
<SCRIPT type="text\Javascript" EVENT="onclick">
var valueCS ;
var valueV ;
var valueVCS ;
var valueStorm ;
var finalValue = valueCS + valueV + valueVCS + valueStorm;
var startOutage ;
var outageEnd ;
document.write="total is "+finalValue;
if(finalValue==0000) {startOutage="28"; outageEnd="1";} else
(finalValue==0001) {startOutage="27"; outageEnd="1";} else
(finalValue==1110) {startOutage="22"; outageEnd="4";} else
(finalValue==1111) {startOutage="24"; outageEnd="4";} else
document.write("Invalid entries")
document.write("Start Outage: "+startOutage<br>"Outage End: "+outageEnd)
</SCRIPT>
</head>
<body>
<form id = "outageSelector" method="post contServer=1000&vistaServer=100&vistaCSServer=10&storm=1&submitServerStatus=View+Outage+Groups">
<fieldset>
<legend><h1>Please choose the status of each system</h1></legend>
<label>Is the contact server up?</label>
<select id="contServer" name="contServer">
<option valueCS=1000>Up</option>
<option valueCS=0>Down</option>
</select><br>
<label>Is the Vista server up?</label>
<select id="vistaServer" name="vistaServer">
<option valueV=100>Up</option>
<option valueV=0>Down</option>
</select><br>
<label>Is VistaCS up?</label>
<select id="vistaCSServer" name="vistaCSServer">
<option valueVCS=10>Up</option>
<option valueVCS=0>Down</option>
</select><br>
<label>Is the outage due to a storm?</label>
<select id="storm" name="storm">
<option valueStorm=1>Yes</option>
<option valueStorm=0>No</option>
</select><br>
<input type="submit" name="submitServerStatus" value="View Outage Groups" />
</fieldset>
</form>
</body>
</html>
The problem you're having is with your FORM. All of your dropdowns had the same name. Also your values were incorrect formatted.
<form id="outageSelector" method="post" action="[SOME_DESTINATION]">
<fieldset>
<legend><h1>Please choose the status of each system</h1></legend>
<label>Is the contact server up?</label>
<select id="contServer" name="contServer">
<option value=1000>Up</option>
<option value=0>Down</option>
</select><br>
<label>Is the Vista server up?</label>
<select id="vistaServer" name="vistaServer">
<option value=100>Up</option>
<option value=0>Down</option>
</select><br>
<label>Is VistaCS up?</label>
<select id="vistaCSServer" name="vistaCSServer">
<option value=10>Up</option>
<option value=0>Down</option>
</select><br>
<label>Is the outage due to a storm?</label>
<select id="storm" name="storm">
<option value=1>Yes</option>
<option value=0>No</option>
</select><br>
<input type="submit" name="submitServerStatus" value="View Outage Groups" />
</fieldset>
</form>
This is sent along w/ the POST behind the scenes:
contServer=1000&vistaServer=100&vistaCSServer=10&storm=1&submitServerStatus=View+Outage+Groups
EDIT: here's a revised js function.
<script>
function checkValues(){
var e;
e = document.getElementById("contServer");
var valueCS = parseInt(e.options[e.selectedIndex].value);
e = document.getElementById("vistaServer");
var valueV = parseInt(e.options[e.selectedIndex].value);
e = document.getElementById("vistaCSServer");
var valueVCS = parseInt(e.options[e.selectedIndex].value);
e = document.getElementById("storm");
var valueStorm = parseInt(e.options[e.selectedIndex].value);
var finalValue = valueCS + valueV + valueVCS + valueStorm;
var startOutage = -1;
var outageEnd = -1;
if(finalValue == 0) {
startOutage = "28";
outageEnd = "1";
} else if (finalValue == 1) {
startOutage = "27";
outageEnd = "1";
} else if (finalValue == 1110) {
startOutage = "22";
outageEnd = "4";
} else if (finalValue == 1111) {
startOutage = "24";
outageEnd = "4";
}
var msg = "total: " + finalValue;
if(startOutage == -1){
msg += " | Start Outage: " + startOutage + " | Outage End: " + outageEnd;
}else{
msg += " | Invalid entries";
}
alert(msg);
}
</script>
You'll need to modify your form to use.
<form id="outageSelector" method="post" action="" onsubmit="checkValues()"> ...
Don't use document.write at all, but DOM manipulation. Read these introductions.
Also, you will need to learn about event-driven programming. You'll need domevents (intro), but also asynchronous communication to the server is event-based. <SCRIPT type="text\Javascript" EVENT="onclick"> is not the way it works :-)
To get output on the screen, you should use console.log along with Firebug, Chrome dev tools, or IE dev tools. See Is there a single HTML5, JavaScript, and CSS debugger?
One obvious problem in your code is
if(finalValue=1110)
Should be (double equals for comparison)
if(finalValue==1110)
But there's another problem, a number that starts with a zero is an octal. That is
010 == 8 // true
It seems like you're after a bitmask
var mask = 0;
var flagA = 1, flagB = 2, flagC = 4;
// Add flagA and flagB to the mask
mask = mask | flagA; // or mask |= flagA
mask |= flagB;
// Now you can test which flags are on using bit testing
// is flagA set?
console.log(mask & flagA) // truthy value
// is flagC set?
console.log(mask & flagC) // false (0)
https://developer.mozilla.org/en/JavaScript/Reference/Operators/Bitwise_Operators
Juan already gave you console.log, which is very useful, and probably the best. Firebug, Chrome Dev and IE dev will also allow you to add break points and watch local and global variables.
Older styles of debugging from the dark ages would include using alert("some string here"); to get a popup or add a debug element to your page and then populating it with
document.getElementById("debugElement").innerHTML("some string here");
Related
Okay to start of this is my main script that does the calculation for my specific problem, I don't understand why it doesn't output the correct result which is "Success" on the specified ID that I put it on. Is it something wrong with the index evaluations or I didn't properly get the index from my form.
function calculatePrice(){
var startLeague;
var targetLeague;
var startDiv;
var targetDiv;
var temp = document.getElementById("startLeague");
startLeague = temp.options[temp.selectedIndex].value;
startLeague = temp.indexOf(startLeague);
temp = document.getElementById("targetLeague");
targetLeague = temp.options[temp.selectedIndex].value;
targetLeague = temp.indexOf(targetLeague);
temp = document.getElementById("startDiv");
startDiv = temp.options[temp.selectedIndex].value;
startDiv = startDiv.indexOf(startDiv);
temp = document.getElementById("targetDiv");
targetDiv = temp.options[temp.selectedIndex].value;
targetDiv = temp.indexOf(targetDiv);
if(startLeague >= targetLeague){
document.getElementById("price-box").innerHTML = "Cannot Calculate";
//Ignore this line
setTimeout(initPrice, 5000);
}else{
if(startDiv >= targetDiv){
document.getElementById("price-box").innerHTML = "Cannot Calculate";
//Ignore this line
setTimeout(initPrice, 5000);
}else{
document.getElementById("price-box").innerHTML = "Success";
}
}
}
This is what I have for my HTML code and represents the values to be taken from the HTML itself via DOM.
<select id="startLeague">
<option value="Someval">0</option>
<option value="Someval1">1</option>
<option value="Someval2">2</option>
<option value="Someval3">3</option>
<option value="Someval4">4</option>
</select>
<select id="targetLeague">
<option value="Someval">0</option>
<option value="Someval1">1</option>
<option value="Someval2">2</option>
<option value="Someval3">3</option>
<option value="Someval4">4</option>
</select>
And so on...
This is my output paragraph that is used to check the value, so far when I click the button it doesn't do anything and remains blank, what is the problem?
<p id="price-box" style="margin: 0; padding: 0;"></p>
Clicking on the button as mentioned above doesn't do anything whereas it should be working.
<button type="button" onclick="calculatePrice()">Calculate</button>
As a final note, yes I have included the following line on the HTML head tag
<script src="price.js"></script>
I have input fields and selects. For different select options there are different equations. After calculating equations, I used .innerHTML to show results. I got first part of the code worked, but I am stuck at the last part. When I try to calculate average of outputs, It shows Nan. Can anyone help with this problem? Thanks in advance.
var container = document.getElementById('container');
var span1 = document.getElementById('span1');
var span2 = document.getElementById('span2');
var output = document.getElementById('output');
function average() {
var a = parseFloat(document.getElementById('a').value);
var b = parseFloat(document.getElementById('b').value);
var c = parseFloat(document.getElementById('c').value);
var d = parseFloat(document.getElementById('d').value);
if (document.getElementById('select1').value == '1') {
span1.innerHTML = ((a+b)/(a*b)).toFixed(2);
} else if (document.getElementById('select1').value == '2') {
span1.innerHTML = ((a*b)/(a+b)).toFixed(2)
} else {
span1.innerHTML = '';
}
if (isNaN(span1.innerHTML)) {
span1.innerHTML = '';
}
if (document.getElementById('select1').value == 'none1') {
span1.innerHTML = 'None'
}
if (document.getElementById('select2').value == '3') {
span2.innerHTML = ((c+d)*100/(c*d)).toFixed(2);
} else if (document.getElementById('select2').value == '4') {
span2.innerHTML = ((c*d)*100/(c+d)).toFixed(2)
} else {
span2.innerHTML = '';
}
if (isNaN(span2.innerHTML)) {
span2.innerHTML = '';
}
if (document.getElementById('select2').value == 'none2') {
span2.innerHTML = 'None'
}
var percent = document.getElementsByClassName('percent');
for (var i = 0; percent.length > i; i++) {
if (percent.length > 0) {
output.innerHTML = percent[i]/(percent.length);
}
}
}
container.addEventListener('change', average);
container.addEventListener('input', average);
<div id="container">
<input id="a" type="number">
<input id="b" type="number">
<select name="abc" id="select1">
<option value="Choose">Choose...</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="none1">None</option>
</select>
<br>
<input id="c" type="number">
<input id="d" type="number">
<select name="abcd" id="select2">
<option value="Choose">Choose...</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="none2">None</option>
</select>
<span id="span1" class="percent"></span>
<span id="span2" class="percent"></span><br>
<span id="output"></span>
</div>
.innerHTML gets or sets the content of an element by invoking the HTML parser on the string passed as the value or extracted from the element. When the content is, or is to become just text (no HTML to be parsed), you should use .textContent as this will not invoke the HTML parser on the content, which saves processing power. In your case, you should be using .textContent.
Now, either way, data sent to or gotten from either .innerHTML or .textContent is a string, so if you want to do math with the value, you need to first convert it to a number. This can be done in several ways:
parseInt(stringToBeConverted, radix)
parseFloat(stringToBeConverted)
Number(stringToBeConverted)
+stringToBeConverted
Now, you have two issues, first when some of the text fields are still empty, their value is an empty string and parseFloat() on an empty string returns NaN. This can be solved by giving each field a default value of 0 in the HTML (i.e. <input id="a" type="number" value="0">).
Second, even with a, b, c, and d all having numeric values, your math:
((a + b) / (a * b)).toFixed(2);
Will result in NaN when a * b results in 0 because that will result in a division by zero situation.
You need to change your algorithm to test for this situation before doing the math.
I have no idea what you're trying to do, but I think this might be the correct solution it's a working way of getting the value of the percent[i] HTML element:
Change
output.innerHTML = percent[i]/(percent.length);
to
output.innerHTML = percent.item(i).innerHTML/(percent.length);
or
output.innerHTML = percent[i].innerHTML/(percent.length);
I have set up a function to take care of my metric conversion an it's not so seamless. I would like to convert lbs to kg and kg to lbs. The problem that i am having is using the jquery change function. It's causing the conversion to only happen on a change but sometimes i just want to due back to back conversions from lbs to kg and it gets stuck and convert the lbs to more lbs or kg to more kg. Any help is appreciated. here is my code below
$("#wUnits").change(function () {
var approx = 2.2;
if ($(this).val() == "lbs") {
value = $("#txtWeight").val() / approx;
$('#wValue').val(value.toFixed(2));
} else if ($(this).val() == "kg") {
value = $("#txtWeight").val() * approx;
$('#wValue').val(value.toFixed(2));
} else {
var value = "";
$('#wValue').val(value);
}
});
and below is my markup
<select id="wUnits">
<option value="">--</option>
<option value="lbs">lbs</option>
<option value="kg">kg</option>
</select>
Ideally what i would like to acheive is a seamless transition between conversions using a dropdown.
What I understand is that you want the conversion to happen not just when you change the value of the <select>
I changed your code a little, it's good to cache the variables in this case, also, I separated the function code to a function named conversion that is triggered on both the <select> change and on keyup or change on your #txtWeight input.
EDIT, implementing Jason Sperske's idea, and added an extra <span> with the resulting units, to avoid confusion. It should be:
HTML:
Convert <input type="text" id="txtWeight" />
<select id="wUnits"><br>
<option value="0">--</option>
<option value="0.45359237">lbs</option>
<option value="2.2">kg</option>
</select><br>
Result: <input type="text" id="wValue" /><span id='rUnits'
JS:
var $units = $("#wUnits");
var $wvalue = $('#wValue');
var $txtweight = $("#txtWeight");
var $runits = $('#rUnits');
$units.change(conversion);
$txtweight.on('keyup change',conversion);
function conversion () {
var value = $txtweight.val() * $units.val();
if(value !== 0) {
$wvalue.val(value.toFixed(2));
$runits.text($units.children(':gt(0):not(:selected)').text());
} else {
$wvalue.val("");
$runits.text('');
}
}
JSBin Demo
I've done a ton of research over the net to come to this code failure :( I have a select list that has an onchange event "emails()". When a certain index value is chosen, I have the javascript pull an array value to populate the "recipient" INPUT value. I know a little javascript, but not enough apparently. Any help would be great, thanks in advance and I apologize if this post isn't "forum correct" it's my first one :)
<html>
<head>
<script type="text/javascript">
function emails() {
var valObj = document.getElementsByName("recipient").value;
var selOpts = document.getElementsById("Concerning");
var selIndex = selOpts.selectedIndex;
var recValue = selOpts.options[selIndex].value;
var jvalObj = new Array()
jvalObj[0]="Empty";
jvalObj[1]="email#1";
jvalObj[2]="email#2";
jvalObj[3]="email#3";
jvalObj[4]="email#4";
jvalObj[5]="email#5";
jvalObj[6]="email#6";
jvalObj[7]="email#7";
jvalObj[8]="email#8";
jvalObj[9]="email#9";
for(i=0; i<selOpts.options.length; i++;)
if (recValue.value=="Benefits")
{valObj.value = jvalObj[1].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[3].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[4].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[5].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[6].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[7].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[8].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[3].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[2].value; break;}
if (selOpts.options[i].selected==true)
{valObj.value = jvalObj[9].value; break;}
}
}</script>
</head>
<body>
<form action="/cgi-bin/formmail" method="post" >
<td width=255 valign=top style='width:191.25pt;padding:0pt 0pt 0pt 0pt'>
<select onChange="javascript:emails();"
" id="Concerning">
<option value="">
<option value="Benefits">Benefits
<option value="Customer_Service">Customer Service
<option value="Employee_Paperwork">Employee Paperwork
<option value="Human_Resources"> Human Resources
<option value="Open_Positions">Open Positions
<option value="Payroll">Payroll
<option value="Quote_Request">Quote Request
<option value="Safety">Safety
<option value="Technical_Support">Technical Support
<option value="Training">Training
<option value="Unemployment">Unemployment
<option value="Workers_Compensation">Workers' Compensation
</select>
</td>
<input TYPE="hidden" NAME="recipient" VALUE="">
<input TYPE="hidden" NAME="subject" VALUE="Contact Form">
<input TYPE="hidden" NAME="email" VALUE="postmaster#company.com">
<input TYPE="hidden" NAME="required" VALUE="Name,Phone,Email,Concerning,Comments">
</form></body>
</html>
Now that I finally get it, this should do the trick.
document.getElementById('Concerning').onchange = function() {
var myArray = ["Empty",
"email#1",
"email#2",
"email#3",
"email#4",
"email#5",
"email#6",
"email#7",
"email#8",
"email#9"];
document.getElementsByName('recipient')[0].value = myArray[this.selectedIndex];
};
Although I might do something like this instead because it is a lot shorter:
document.getElementsByName('recipient')[0].value = 'email#' + this.selectedIndex;
I think this is a whole lot simpler than you are making it. If I am interpreting your code correctly, all you want to do is take the selected value of the list and stick it into the hidden input recipient. In that case you can pass this to the onChange declaration. The new selected value will be the value of that list. Finally, get the hidden input and set the value there.
http://jsfiddle.net/pvvQd/
<select onChange="emails(this);" id="Concerning">
In this code the function emails accepts a single parameter. We pass this to that parameter which is the select list. You used getElementsByName incorrectly in your original code. This returns an array of elements with that name (as name isn't unique per page). So assuming there is only one we retrieve the zero index. You should probably give that field an id and retrieve it by that instead. Finally we just set the hidden fields value to the select list's value.
function emails(elem) {
//you should probably give this an id and retrieve using that instead
var recipients = document.getElementsByName('recipient')[0];
recipients.value = elem.value;
}
Actually, if you wanted to make this super short you could do:
http://jsfiddle.net/pvvQd/1/
I would encourage you to stay away from inline javascript declarations. Instead you can do something like this. That way your code and html are not intertwined.
http://jsfiddle.net/pvvQd/2/
document.getElementById('Concerning').onchange = function() {
document.getElementsByName('recipient')[0].value = this.value;
};
I think you have a cut-n-paste error. document.getElementsById should be document.getElementById as it only grabs a single element.
There is also an error with an extra " <select onChange="javascript:emails();" " id="Concerning"> should be <select onChange="javascript:emails();" id="Concerning">
Also you onChange should just be onChange="emails();" don't need to add "javascript:"
Try changing inputs to have an ID value not just name that way instead of using document.getElementsByName (which returns an array and why your valObj.value assignment fails as it should be valObj[0].value = ) you can use document.getElementById("recipient")
You are also checking for the value of recValue here if (recValue.value=="Benefits")
when that variable is already the value so it should be recValue == "Benefits".
You don't need to go through all of the element as you already have the selected index and could just act off of that single value. The loop is just overkill. Not certain what you are trying to achieve there.
Suggested edits to the original source code, see comments for edits.
function emails()
{
var valObj = document.getElementsByName("recipient").value;
var selOpts = document.getElementsById("Concerning");
var selIndex = selOpts.selectedIndex;
var recValue = selOpts.options[selIndex].value;
/*Since the array will assing default integer indices where keys don't exist
we can rewrite the array as follows to spare redundant write access to it*/
var jvalObj = new Array("Empty", "email#1", "email#2", "email#3", "email#4",
"email#5", "email#6", "email#7", "email#8", "email#9");
for(i=0; i<selOpts.options.length; i++){
if (recValue.value=="Benefits"){
valObj.value = jvalObj[1].value;
i = selOpts.options.length;
/*Each of the deleted conditionals used the same comparison which means
that they will never meet their criteria without first meeting this
conditional, which was set to break the loop*/
}else if (selOpts.options[i].selected==true){
valObj.value = jvalObj[i].value;
/*Personal preference: unless you're bound to the use of break I'd leave use i = len
- the exception being where you'd want to retain i of course
*/
i = selOpts.options.length;
}
}
The html
<!-- DOM events carry out javascript callbacks by default -->
<select onChange="emails();" id="Concerning">
<!DOCTYPE html>
<html lang="eng">
<head>
<script type="text/javascript">
function emails()
{
var recipient = document.getElementById("recipient");
var concerning = document.getElementById("Concerning");
var recipientEmailToSet = concerning.options[concerning.selectedIndex].value;
recipient.value = recipientEmailToSet;
//Remove next line for alert to go away
alert(recipient.value);
}
</script>
</head>
<body>
<form action="/cgi-bin/formmail" method="post" >
<td width=255 valign=top style='width:191.25pt;padding:0pt 0pt 0pt 0pt'>
<select onChange="emails();" id="Concerning">
<option value=""></option>
<option value="email#1">Benefits</option>
<option value="email#2">Customer Service</option>
<option value="email#3">Employee Paperwork</option>
<option value="email#4"> Human Resources</option>
<option value="email#5">Open Positions</option>
<option value="email#6">Payroll</option>
<option value="email#7">Quote Request</option>
<option value="email#8">Safety</option>
<option value="email#9">Technical Support</option>
<option value="email#10">Training</option>
<option value="email#11">Unemployment</option>
<option value="email#12">Workers' Compensation</option>
</select>
</td>
<input TYPE="hidden" id="recipient" VALUE="" />
<input TYPE="hidden" id="subject" VALUE="Contact Form" />
<input TYPE="hidden" id="email" VALUE="postmaster#company.com" />
<input TYPE="hidden" id="required" VALUE="Name,Phone,Email,Concerning,Comments" />
</form>
</body>
</html>
I am trying to learn how to write cookies to keep the data in my CookieButton1 button persistent and to survive refreshes and page reloads. How can I do this in JavaScript?
I have supplied my source code. Any advise, links or tutorials will be very helpful.
If you navigate to [http://iqlusion.net/test.html][1] and click on Empty1, it will start to ask you questions. When finished it stores everything into CookieButton1. But when I refresh my browser the data resets and goes away.
Thanks!
<html>
<head>
<title>no_cookies>
</head>
<script type="text/javascript" >
function setCookie(c_name,value,expiredays)
{
var exdate=new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie=c_name+ "=" +escape(value)+
((expiredays==null) ? "" : ";expires="+exdate.toUTCString());
}
function getCookie(c_name)
{
if (document.cookie.length>0)
{
c_start=document.cookie.indexOf(c_name + "=");
if (c_start!=-1)
{
c_start=c_start + c_name.length+1;
c_end=document.cookie.indexOf(";",c_start);
if (c_end==-1) c_end=document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end));
}
}
return "";
}
function checkCookie()
{
CookieButton1=getCookie('CookieButton1');
if (CookieButton1!=null && CookieButton1!="")
{
alert('Welcome again '+CookieButton1+'!');
}
else
{
if (CookieButton1!=null && CookieButton1!="")
{
setCookie('CookieButton1',CookieButton1,365);
}
}
}
var Can1Set = "false";
function Can1()
{
if (Can1Set == "false")
{
Can1Title = prompt("What do you want to name this new canned response?","");
Can1State = prompt("Enter a ticket state (open or closed)","closed");
Can1Response = prompt("Enter the canned response:","");
Can1Points = prompt("What point percentage do you want to assign? (0-10)","2.5");
// Set the "Empty 1" button text to the new name the user specified
document.CookieTest.CookieButton1.value = Can1Title;
// Set the cookie here, and then set the Can1Set variable to true
document.cookie = "CookieButton1";
alert(document.cookie);
Can1Set = true;
}else{
document.TestForm.TestStateDropDownBox.value = Can1State;
document.TestForm.TestPointsDropDownBox.value = Can1Points;
document.TestForm.TestTextArea.value = Can1Response;
// document.TestForm.submit();
}
}
</script>
<form name=TestForm>
State: <select name=TestStateDropDownBox>
<option value=new selected>New</option>
<option value=open selected>Open</option>
<option value=closed>Closed</option>
</select>
Points: <select name=TestPointsDropDownBox>
<option value=1>1</option>
<option value=1.5>1.5</option>
<option value=2>2</option>
<option value=2.5>2.5</option>
<option value=3>3</option>
<option value=3.5>3.5</option>
<option value=4>4</option>
<option value=4.5>4.5</option>
<option value=5>5</option>
<option value=5.5>5.5</option>
<option value=6>6</option>
<option value=6.5>6.5</option>
<option value=7>7</option>
<option value=7.5>7.5</option>
<option value=8>8</option>
<option value=8.5>8.5</option>
<option value=9>9</option>
<option value=9.5>9.5</option>
<option value=10>10</option>
</select>
<p>
Ticket information:<br>
<textarea name=TestTextArea cols=50 rows=7></textarea>
</form>
<form name=CookieTest>
<input type=button name=CookieButton1 value="Empty 1" onClick="javascript:Can1()">
</form>
// Set the cookie here, and then set the Can1Set variable to true
document.CookieTest.CookieButton1 = "CookieButton1";
You aren't setting the cookie here. You are attempting to change the button element with the name CookieButton1 of the form with the name CookieTest to a String value "CookieButton1". This would have shown a JavaScript error in the average webbrowser.
To set a real cookie, you need document.cookie. You can find a little tutorial at w3schools.
document.cookie = "CookieButton1";
All that is doing is setting a cookie without a value, only a name. Cookies are defined as a 'name=value' pairing.
It should look like this ( or equivalent )
document.cookie = 'cookieID=CookieButton1';
Setting document.cookie = will NOT overwrite existing cookies, simply append information to the established cookie.
If you wanted to delete all cookies set by YOUR domain you can always use the following script
function delCookie() {
var new_date = new Date()
new_date = new_date.toGMTString()
var thecookie = document.cookie.split(";")
for (var i = 0; i < thecookie.length; i++) {
document.cookie = thecookie[i] + "; expires =" + new_date
}
}
If you need to remove cookies individually, the removeCookie function you have will suffice, but only if it is in a name=value pairing. Else your cookie is unusable since it will contain no data just a name.
Your cookie value works as far as saving the data yes, however once you click refresh the can1set variable is set back to the value of false so the browser is seeing it as null when it runs the checkCookie() function. In my chat program im currently working on I had a simular issue until I set a variable in my checkCookie() function to check against. That way i wasn't always checking against a false value and returning null to my if statement.
like so...
function checkCookie()
{
var username=getCookie("username");
if (username!=null && username!="")
{
//if username is NOT null and is not blank asigns it to idname
document.getElementById("idname").innerHTML= document.getElementById("idname").innerHTML += username;
}
else
{
//if username IS null or blank prompt user to enter name
username=prompt("Please enter your name:","");
if (username!=null && username!="")
{
setCookie("username",username,1);
}
else
{
//if user submits a null or blank value close browser
byebye();
}
}
}