| jmrker |
09-24-2012 02:13 AM |
Checkbox value storage
'xelawho' had a short snippet of code
See post #3 of: http://www.codingforums.com/showthread.php?t=273928
that served a purpose for me in some other program. See 2 versions below. :thumbsup:
Code:
<body>
<input type="checkbox" value="hi" onclick="addMess(this)"/><br>
<input type="checkbox" value="bye" onclick="addMess(this)"/><br>
<input type="checkbox" value="later" onclick="addMess(this)"/><br>
<input type="button" value="show me" onclick="alert(str)"/>
<script type = "text/javascript">
var str=""
function addMess(box){
str=box.checked?str+box.value+"\n":str.replace(box.value+"\n","");
}
</script>
</body>
Version 1 using string
Code:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title> Untitled </title>
<style type="text/css">
#fldFaculty { width:200px; }
</style>
</head>
<body>
<fieldset id="fldFaculty"><legend>Choose faculty to notify</legend>
<script type="text/javascript">
// Modified from: http://www.codingforums.com/newreply.php?do=newreply&p=1272610
var Faculty = ['John','Jacob','Jingle-Heimer','Smith'];
var str = '';
for (var i=0; i<Faculty.length; i++) {
str += '<label><input type="checkbox" value="'+Faculty[i]+'" onclick="addMess(this)"/>'+Faculty[i]+'</label><br>';
}
document.write(str); // create display
var FacultyList = "";
function addMess(box){
FacultyList=box.checked?FacultyList+box.value+"\n":FacultyList.replace(box.value+"\n","");
}
</script>
</fieldset>
<input type="button" value="Show chosen" onclick="alert(FacultyList)"/>
</body>
</html>
Version 2 using array
Code:
<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8" />
<title> Untitled </title>
<style type="text/css">
#fldFaculty { width:200px; }
</style>
</head>
<body>
<fieldset id="fldFaculty"><legend>Choose faculty to notify</legend>
<script type="text/javascript">
// Modified from: http://www.codingforums.com/newreply.php?do=newreply&p=1272610
var Faculty = ['John','Jacob','Jingle-Heimer','Smith'];
var str = '';
for (var i=0; i<Faculty.length; i++) {
str += '<label><input type="checkbox" value="'+Faculty[i]+'" onclick="addMess(this)"/>'+Faculty[i]+'</label><br>';
}
document.write(str); // create display
Array.prototype.inArray = function (value) {
// Returns position of match in array if found or -1 if not
for (var i=0; i < this.length; i++) {
// Matches identical (===), not just similar (==).
if (this[i] === value) { return i; }
}
return -1;
};
var FacultyList = [];
function addMess(box){
if (box.checked) { FacultyList.push(box.value); }
else {
var p = FacultyList.inArray(box.value);
FacultyList.splice(p,1);
}
}
</script>
</fieldset>
<input type="button" value="Show chosen" onclick="alert(FacultyList.join(','))"/>
<!-- Alternative display -->
<!-- input type="button" value="Show chosen" onclick="alert(FacultyList.join('\n'))"/ -->
</body>
</html>
|