Implement a dynamic selectbox in html - php

I am trying to develop a select box so that I can change the selected option dynamically
e.g.
selectbox option display message
---------------------------------------------
field 1 text
field 2 integer
field 3 bool
There are three select boxes. The first select box provide three options.
when select box 1 is selected, the other select boxes will have only 2 options (excluding the selected one)
When select box 2 is selected, the other select boxes will have only 1 option (excluding the selected two)
When a select box's value changes, the appropriate message is displayed.
All of the text that will be displayed is read in from a database as an array in the following format:
name text
id integer
address text
Then I create a select box with the three option
When I set select box 1's value as name, the text message is displayed, and so on.
How should I implement this? (I hope you get my idea) Thank you again for your help.
Thank you

I'd suggest something akin to the following:
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset');
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};​
JS Fiddle demo.
Edited to add the messages, as requested in comments (which I overlooked in the actual question...):
var sel1 = document.getElementById('one'),
sel2 = document.getElementById('two'),
sel3 = document.getElementById('three'),
sels = document.getElementsByTagName('select'),
reset = document.getElementById('reset'),
msgs = ['text','integer','boolean'];
function disableOpts(elem) {
for (var i = 0, len = sels.length; i < len; i++) {
if (sels[i] != elem) {
var opts = sels[i].getElementsByTagName('option');
for (var c = 0, leng = opts.length; c < leng; c++) {
if (c == elem.selectedIndex) {
opts[c].disabled = true;
}
}
}
}
hideMessage(elem);
};
function displayMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = msgs[i];
span.style.display = 'block';
}
}
};
function hideMessage(elem){
for (var i=0,len=sels.length;i<len;i++){
if (sels[i] == elem){
var span = elem.parentNode.getElementsByTagName('span')[0];
span.innerHTML = '';
span.style.display = 'none';
}
}
};
sel1.onchange = function() {
disableOpts(this);
};
sel2.onchange = function() {
disableOpts(this);
};
sel3.onchange = function() {
disableOpts(this);
};
sel1.onfocus = function() {
displayMessage(this);
};
sel2.onfocus = function() {
displayMessage(this);
};
sel3.onfocus = function() {
displayMessage(this);
};
sel1.onblur = function() {
hideMessage(this);
sel2.onblur = function() {
hideMessage(this);
};};
sel3.onblur = function() {
hideMessage(this);
};​​
JS Fiddle demo.

Take a look at this plugin, maybe it can help you.
For the data than you can put a php foreach for the <option> element on the select.

Related

Autocomplete Box Only Shows First Letter

I am trying to make a text box that when you type in it, it pulls up suggestions underneath that come from a recordset. For some reason when you type in the field, I only get the first letter. It think it has to do with the json_encode part. When I changed the array to be just text: "Brainpop","Google", etc. it worked fine. Any thoughts? This is the coding I based it off of:
https://www.w3schools.com/howto/howto_js_autocomplete.asp
<script type="application/javascript">
function autocomplete(inp, arr) {
/*the autocomplete function takes two arguments,
the text field element and an array of possible autocompleted values:*/
var currentFocus;
/*execute a function when someone writes in the text field:*/
inp.addEventListener("input", function(e) {
var a, b, i, val = this.value;
/*close any already open lists of autocompleted values*/
closeAllLists();
if (!val) { return false;}
currentFocus = -1;
/*create a DIV element that will contain the items (values):*/
a = document.createElement("DIV");
a.setAttribute("id", this.id + "autocomplete-list");
a.setAttribute("class", "autocomplete-items");
/*append the DIV element as a child of the autocomplete container:*/
this.parentNode.appendChild(a);
/*for each item in the array...*/
for (i = 0; i < arr.length; i++) {
/*check if the item starts with the same letters as the text field value:*/
if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
/*create a DIV element for each matching element:*/
b = document.createElement("DIV");
/*make the matching letters bold:*/
b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
b.innerHTML += arr[i].substr(val.length);
/*insert a input field that will hold the current array item's value:*/
b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
/*execute a function when someone clicks on the item value (DIV element):*/
b.addEventListener("click", function(e) {
/*insert the value for the autocomplete text field:*/
inp.value = this.getElementsByTagName("input")[0].value;
/*close the list of autocompleted values,
(or any other open lists of autocompleted values:*/
closeAllLists();
});
a.appendChild(b);
}
}
});
/*execute a function presses a key on the keyboard:*/
inp.addEventListener("keydown", function(e) {
var x = document.getElementById(this.id + "autocomplete-list");
if (x) x = x.getElementsByTagName("div");
if (e.keyCode == 40) {
/*If the arrow DOWN key is pressed,
increase the currentFocus variable:*/
currentFocus++;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 38) { //up
/*If the arrow UP key is pressed,
decrease the currentFocus variable:*/
currentFocus--;
/*and and make the current item more visible:*/
addActive(x);
} else if (e.keyCode == 13) {
/*If the ENTER key is pressed, prevent the form from being submitted,*/
e.preventDefault();
if (currentFocus > -1) {
/*and simulate a click on the "active" item:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*a function to classify an item as "active":*/
if (!x) return false;
/*start by removing the "active" class on all items:*/
removeActive(x);
if (currentFocus >= x.length) currentFocus = 0;
if (currentFocus < 0) currentFocus = (x.length - 1);
/*add class "autocomplete-active":*/
x[currentFocus].classList.add("autocomplete-active");
}
function removeActive(x) {
/*a function to remove the "active" class from all autocomplete items:*/
for (var i = 0; i < x.length; i++) {
x[i].classList.remove("autocomplete-active");
}
}
function closeAllLists(elmnt) {
/*close all autocomplete lists in the document,
except the one passed as an argument:*/
var x = document.getElementsByClassName("autocomplete-items");
for (var i = 0; i < x.length; i++) {
if (elmnt != x[i] && elmnt != inp) {
x[i].parentNode.removeChild(x[i]);
}
}
}
/*execute a function when someone clicks in the document:*/
document.addEventListener("click", function (e) {
closeAllLists(e.target);
});
}</script>
<script>
//now put it into the javascript
var software_list = <?php echo json_encode($types2, JSON_UNESCAPED_SLASHES), "\n"; ?>;
</script>
<?php
$query1 = "SELECT software_name from software";
$result = mysqli_query($sdpc_i, $query1);
$types = array();
while ($row = $result->fetch_assoc()) {
$types[] = '"'.$row['software_name'].'"';
}
$types2 = implode(",",$types);
?>
<div class="autocomplete"><input type="text" name="software_name" id="myInput" class="form-control col-md-8" value="" required></div><script>
autocomplete(document.getElementById("myInput"), software_list);
</script>
</div>

Store data to database continuously without pressing 'Submit' og 'Next'

I am a student who will conduct an experiment online.
The participants go to a website (a more complex version of this one: http://auforskning.rf.gd/TEST2.php) which will track a) which buttons they press and b) how long time the buttons are pushed. This is to track how many seconds each participant spend on reading the information.
However, there is one problem: The participants have to press 'Submit' or 'Next' in order to store the informations. If they read the information behind the boxes (as intended) and just close the window, the data will be lost.
Is there a way to store data continuously, so that the data isn't lost if they just close the window?
mlweb.js-file:
dtNewDate = new Date();
starttime = dtNewDate.getTime(); // abs. starttime of experiment
// set vars for delay
prevtime = 0; // memory in timefunction to compensate for delay
dtime=0;
prevCell = -1; // delay lag memory (-1 means first cell is not delayable
loaded = false; // flag to test whether page has been loaded 9is set to true in reorder
boxOpen = false; // flag to test whether box is already open (using in showCont and hideCont)
chkFrm = false // flag to test whether additional form elements have to be checked on submission
warningTxt = "Some questions have not been answered. Please answer all questions before continuing!";
CBpreset = false; // flag to set CB order fixed by a matrix on forehand: default is set to false
prevfieldname = ""; // default for switching clicks
transpImg = new Image()
tempImg = new Image()
previousSrc="";
// default values
mlweb_outtype="XML";
mlweb_fname=0;
masterCond = 1; // number of master conditions
randomOrder = false; // force randomize of counterbalancing order
subject="";
evtOpen = 0;
evtClose = 0;
tmDirectStart = false;
tmTimeUp = false;
tmActive = false;
tmCurTime = 0;
// get source transparant image
transpImg.src="transp.gif"
function abc_num(str)
{
out=str.toUpperCase().charCodeAt(0)-65;
return out
}
function fac(x)
{
// Faculty: x!=x(x-1)...1
var outp=1;
for (var i=1; i<=x; i++)
{outp=outp*i}
return outp
}
function CountBal(subjnr, num)
{
// counterbalance based on subj number.
// first subject is 0
// Num is number of options to counterbalance
// (number of orders is Num!)
var numOrd=fac(num);
start = subjnr - numOrd*Math.floor((subjnr-1)/numOrd)
orderstr=""
for (var i=0;i<num;i++)
{orderstr+=i.toString()}
outstr=""
for (var i=num; i>0; i--)
{
var den=fac(i-1);
pos = Math.floor((start-1)/den)+1
outstr+=orderstr.charAt(pos-1)+","
orderstr = orderstr.substring(0,pos-1)+orderstr.substr(pos)
start=start-(pos-1)*den
}
outstr=outstr.substr(0,outstr.length-1)
return outstr.split(",")
}
function ExpMatrix(M)
{ // expand data matrices
var Mrows=M.split("`");
var outM = new Array();
for (rowcount=0;rowcount<Mrows.length;rowcount++)
{
outM[rowcount]=Mrows[rowcount].split("^")
}
return outM;
}
function ExpRow(M)
{ // expand data vectors
var outM = new Array();
outM = M.split("^")
return outM;
}
function btnHover(loc,act)
{
if (act=='out')
{
if (loc.className.indexOf(" ")>0) {tempstyle= loc.className.substring(0,loc.className.indexOf(" "));}
}
else
{tempstyle=loc.className + ' btnhov';}
loc.className=tempstyle;
}
function timefunction(event,name,value) {
// Record proc data in form element
mlweb_form=document.forms[mlweb_fname].elements['procdata']
dtNewDate = new Date();
eventtime = dtNewDate.getTime();
var curtime = eventtime-starttime-dtime; // dtime is to compensate for delay time (failed openings have negative time!
// if (prevtime>curtime) {curtime=prevtime;} else {prevtime=curtime}; // check with previous event time: if smaller, then delay was not finished: set curtime to prevtime so event has duration 0;
dtime=0; // reset dtime
if (mlweb_outtype=="XML")
{
var str="<eventblock><event>"+event+"</event><name>"+name+"</name><value>"+value+"</value><time>"+curtime+"</time></eventblock>";
var headerstr="<?xml version=1.0?>"
}
else
{
var str="\""+event+"\",\""+name+"\",\""+value+"\",\""+curtime+"\"\n"
var headerstr="\"event\",\"name\",\"value\",\"time\"\n"
};
if(mlweb_form.value=='')
{
mlweb_form.value=headerstr;
}
mlweb_form.value+=str;
if (event=="onload") {reorder();}
return true;
}
// convert event to eventdata and call save function
function RecordEventData(objActionElement, objEvent)
{
var strName, strEventType, strFormValue;
strName = objActionElement.name;
strFormValue = (objActionElement.value) ? objActionElement.value : "";
strEventType = objEvent.type;
//call timefunction
timefunction(strEventType,strName, strFormValue)
return false;
}
function checkForm(formHandle)
{
if (chkFrm)
{
noElm = document.forms[mlweb_fname].elements.length;
var filled=true;
for (i=0;i<noElm;i++)
{
elemHandle = document.forms[0].elements[i];
if (elemHandle.type=="hidden") {continue};
if (elemHandle.value=="") {filled = false; break};
if (elemHandle.type=="select-one") {if (elemHandle.options[elemHandle.selectedIndex].value=="") {filled = false; break};}
if (elemHandle.type=="radio") // procedure to check radio buttons
{
radio_name=elemHandle.name; // get name (needed to retrieve length)
// get length of radio button group
r_length = eval("document.forms[0]."+radio_name).length
for (ri=0;ri<r_length;ri++) // check each button and break loop if checked button was found
{ radioHandle = document.forms[0].elements[i+ri];
if (radioHandle.checked) {filled=true; break} else {filled=false};
}
if (filled) {i=i+r_length-1; continue} else {break}; // if checked button found; continue
// else break loop and show warning
}
}
if (!filled) {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
if ((chkchoice=="nobuttons") | !chkFrm) {return true;}
if (chkchoice==true) {timefunction('submit','submit','succeeded');return true} else {alert(warningTxt);timefunction('submit','submit','failed');return false};
}
function objElem(name,value)
{
this.name=name
this.value=value
}
function ShowCont(fieldname, objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurs. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem = new objElem
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (boxOpen) {return;}
if (evtClose<3) {boxOpen = true;} //set flag to show box is open
// retrieve tagname and txt for this cell
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
}
function HideCont(fieldname,objEvent)
{
if (!loaded) {return;} // do not open boxes when page is loading
if (!boxOpen) {return;} // do not close boxes that are not open...
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
boxOpen = false; // set tag to show that box is closed again
thisElem = new objElem;
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
function SwitchCont(fieldname, objEvent)
{
// special function for clicking tasks
if (!loaded) {return;} // do not open boxes when page is loading
if (!tmDirectStart & tmActive & tmCurTime==0) {startTmBar();}
if (tmTimeUp) {return;}
// check if a click on a link (A) occurred. this happens for example
// when a mlweb A link gets a focus (due to clicking the box) and a subject presses enter
// this is to prevent enters from generating events when in click (rather than mouseover) mode
if (objEvent.srcElement)
{
if (objEvent.srcElement.nodeName=="A") {return}
}
else if (objEvent.target)
{
if (objEvent.target.nodeName=="A") {return}
}
thisElem = new objElem
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
// check if open cell should be recorded
if ((statecont[RowOut[row]][ColOut[col]]=="0") & !(recOpenCells)) {return;}
if (fieldname==prevfieldname)
{
// just close current box if box is same as previous
window.clearTimeout(delay);
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
prevfieldname="";
}
else
{
if ((prevfieldname!="")&(evtClose==1))
{
// first close prev box if box is not same as previous
window.clearTimeout(delay);
var row = abc_num(prevfieldname);
var col = parseInt(prevfieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
// save procesdata
RecordEventData(thisElem, objEvent)
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(prevfieldname+"_txt");
HandleBox = document.getElementById(prevfieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+prevfieldname+"_txt"+"']");
HandleBox=eval("document.all['"+prevfieldname+"_box"+"']");
}
HandleTxt.style.visibility='hidden';HandleBox.style.visibility='visible';
}
if ((prevfieldname=="")|(evtClose==1))
{
// only if any box may be opened or there as no previous box open, show content
var row = abc_num(fieldname);
var col = parseInt(fieldname.substr(1));
thisElem.name = tagcont[RowOut[row]][ColOut[col]];
thisElem.value = txtcont[RowOut[row]][ColOut[col]];
RecordEventData(thisElem, objEvent);
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTxt = document.getElementById(fieldname+"_txt");
HandleBox = document.getElementById(fieldname+"_box");
}
else if (document.all)
{
//IE4/5
HandleTxt=eval("document.all['"+fieldname+"_txt"+"']");
HandleBox=eval("document.all['"+fieldname+"_box"+"']");
}
// delay
currCell = -1;
for (var i=0;i<Dlist.length;i++)
{if (tagcont[RowOut[row]][ColOut[col]]==Dlist[i]) {currCell=i;break;}}
if ((prevCell!=-1)&(currCell!=-1)) {dtime = DTimes[currCell][prevCell];} else {dtime=0};
prevCell = currCell;
//HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';
delay=window.setTimeout("HandleTxt.style.visibility='visible';HandleBox.style.visibility='hidden';",dtime) //make image transparant
prevfieldname=fieldname;
}
}
}
function recChoice(eventname ,name, value)
{
chkchoice = true;
timefunction(eventname, name, value);
if (document.forms[mlweb_fname].choice) {document.forms[mlweb_fname].choice.value = name;}
if (btnType=="button")
{
for (i=0;i<btnTxt.length;i++)
{
if (btnFlg==1) {btnNum = ColOut[i]} else {btnNum = RowOut[i]};
HandleBut = eval("document.forms['"+mlweb_fname+"']."+btnTag[btnNum]);
if (btnTag[btnNum]==name) {HandlePressed = HandleBut};
if (btnState[btnNum]=="1") {HandleBut.className = 'btnStyle';}
}
HandlePressed.className='pressedStyle btnHov';
}
}
function loadMatrices()
{
// get settings data from script in body
txtcont = ExpMatrix(txt);
statecont = ExpMatrix(state);
tagcont = ExpMatrix(tag);
boxcont = ExpMatrix(box);
WidthCol = ExpRow(W_Col);
HeightRow = ExpRow(H_Row);
DTimes = ExpMatrix(delay);
CountCol = ExpRow(CBCol);
CountRow = ExpRow(CBRow);
btnTxt = ExpRow(btntxt);
btnTag = ExpRow(btntag);
btnState = ExpRow(btnstate);
// new in version 99.2: CB preset matrix
if (CBpreset) {
CBorder = ExpMatrix(CBord);
}
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{ColOut[i]=i;}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{RowOut[i]=i;}
Dlist = new Array();
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
}
}
}
function reorder()
{
// if referer present (or other php/asp code) then get current hit number
if (document.cookie.indexOf("mlweb_subject=")!=-1)
{
subjstr=document.cookie;
subject=subjstr.substr(subjstr.indexOf("mlweb_subject=")+14);
}
if (document.cookie.indexOf("mlweb_condnum=")!=-1)
{
subjstr=document.cookie;
subjnr=parseInt(subjstr.substr(subjstr.indexOf("mlweb_condnum=")+14));
subjtype = "cookie";
//alert(subjnr + " " + subjtype);
}
else
{
if (typeof ref_cur_hit!="undefined")
{subjnr = ref_cur_hit; subjtype = "header"}
else
{
subjnr=-1; subjtype = "random";
}
}
// if subj nr turns out to be not a number, or randomizer is set to true then set it to randomize
if (isNaN(subjnr)|randomOrder) {subjnr=-1; subjtype = "random";}
if (document.forms[mlweb_fname].condnum) {document.forms[mlweb_fname].condnum.value = subjnr;}
if (document.forms[mlweb_fname].expname) {document.forms[mlweb_fname].expname.value = expname;}
if (document.forms[mlweb_fname].nextURL) {document.forms[mlweb_fname].nextURL.value = nextURL;}
if (document.forms[mlweb_fname].subject) {document.forms[mlweb_fname].subject.value = subject;}
if (document.forms[mlweb_fname].to_email) {document.forms[mlweb_fname].to_email.value = to_email;}
if (CBpreset)
{
if (subjnr==-1) {subjnr=Math.floor(Math.random()*CBorder.length)}
// CB order is preset in a matrix
curord = Math.floor(subjnr/masterCond) % CBorder.length;
cbcount=0;
for (var i=0; i<CountCol.length; i++)
{
ColOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++;
}
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
RowOut[i]=parseInt(CBorder[curord][cbcount]);
cbcount++
}
}
else
{
// code if no prespecified CBorder
// retrieve position of counterbalance groups
var cf=new Array() // position of fixed cols
var c1=new Array() // position of c1 cols
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': cf[cf.length]=i;break;
case '1': c1[c1.length]=i;break;
}
}
var rf=new Array() // position of fixed rows
var r1=new Array() // position of c1 rows
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': rf[rf.length]=i;break;
case '1': r1[r1.length]=i;break;
}
}
// subjDen is the denominator used to devide the subj number for each counterbalance step
subjDen = 1;
if (subjtype!="random") {subjDen = Math.floor(subjDen * masterCond)};
// first determine column and row connects and switch on that
var numCond = (c1.length>0 ? fac(c1.length) : 1)*(r1.length>0 ? fac(r1.length) : 1);
if (subjnr==-1) {subjnr=Math.floor(Math.random()*numCond)}
//alert("total cond:" + numCond+"\nsubject: "+subjnr);
// counterbalance col groups
if (c1.length>0) {c1_order=CountBal(subjnr/subjDen+1,c1.length);
subjDen = subjDen*fac(c1.length);}
var c1count=0;
ColOut = new Array();
for (var i=0; i<CountCol.length; i++)
{
switch (CountCol[i])
{
case '0': ColOut[i]=i;break;
case '1': ColOut[i]=c1[c1_order[c1count]];c1count++;break;
}
}
// counterbalance rows
if (r1.length>0) {r1_order=CountBal(subjnr/subjDen+1,r1.length); subjDen = subjDen * fac(r1.length);}
var r1count=0;
RowOut = new Array();
for (var i=0; i<CountRow.length; i++)
{
switch (CountRow[i])
{
case '0': RowOut[i]=i;break;
case '1': RowOut[i]=r1[r1_order[r1count]];r1count++;break;
}
}
}
Dlist=new Array();
// reorder and resize table content
for (j=0;j<RowOut.length;j++)
{
for (i=0;i<ColOut.length;i++)
{
var label = String.fromCharCode(j+97)+i.toString();
if (statecont[j][i]=="1") {Dlist[Dlist.length]=tagcont[j][i];}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleCont = document.getElementById(label+"_cont");
HandleTxt = document.getElementById(label+"_txt");
HandleBox = document.getElementById(label+"_box");
HandleTD = document.getElementById(label+"_td");
HandleTDbox = document.getElementById(label+"_tdbox");
HandleImgBox = document.getElementById(label+"_img");
HandleImg = eval("document.images."+label);
pxstr="px";
}
else if (document.all)
{
//IE4/5
HandleCont=eval("document.all['"+label+"_cont"+"']");
HandleTxt=eval("document.all['"+label+"_txt"+"']");
HandleTD=eval("document.all['"+label+"_td"+"']");
HandleBox=eval("document.all['"+label+"_box"+"']");
HandleTDbox=eval("document.all['"+label+"_tdbox"+"']");
HandleImgbox=eval("document.all['"+label+"_img"+"']");
HandleImg = eval("document.images."+label);
pxstr="px";
}
// set txt
HandleTD.innerHTML =""; // empty for IE5 on mac bug
// if txtcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (txtcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTD.innerHTML = " "}
else {
// if boxes are non-active and labels are fixed, header rows should also be fixed
if (statecont[RowOut[j]][ColOut[i]]=="0")
{
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTD.innerHTML = txtcont[temprow][tempcol];
}
else {HandleTD.innerHTML = txtcont[RowOut[j]][ColOut[i]]};
};
HandleTDbox.innerHTML =""; // empty for IE5 on mac bug
// if boxcont is empty or only contains spaces then replace by nbsp to keep TD layout
if (boxcont[RowOut[j]][ColOut[i]].replace(/[\x20]/gi, "")=="") {HandleTDbox.innerHTML = " "}
else {
if (colFix) {tempcol = i}
else {tempcol=ColOut[i]};
if (rowFix) {temprow = j}
else {temprow = RowOut[j]};
HandleTDbox.innerHTML = boxcont[temprow][tempcol];
};
//set sizes
HandleTD.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTD.height = parseInt(HeightRow[RowOut[j]])-5;
HandleTDbox.width = parseInt(WidthCol[ColOut[i]])-5;
HandleTDbox.height = parseInt(HeightRow[RowOut[j]])-5;
if (statecont[RowOut[j]][ColOut[i]]=="1") {HandleTD.className = activeClass;} else {HandleTD.className = inactiveClass};
HandleCont.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleCont.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleTxt.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleTxt.style.clip = "rect(0px "+ HandleTxt.style.width + " " + HandleTxt.style.height +" 0px)";
HandleBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleBox.style.clip = "rect(0px "+ HandleBox.style.width + " " + HandleBox.style.height +" 0px)";
HandleImgBox.style.width = parseInt(WidthCol[ColOut[i]])+pxstr;
HandleImgBox.style.height = parseInt(HeightRow[RowOut[j]])+pxstr;
HandleImg.height = parseInt(HeightRow[RowOut[j]]);
HandleImg.width = parseInt(WidthCol[ColOut[i]]);
// open state=0 boxes using img names from imgcont matrix
if (statecont[RowOut[j]][ColOut[i]] == '0') {HandleBox.style.visibility = "hidden"; HandleTxt.style.visibility = "visible";} else {HandleBox.style.visibility = "visible"; HandleTxt.style.visibility = "hidden";}
}
}
// if there are buttons then reorder the buttons according to the counterbalancing scheme
if (btnFlg>0)
{
btn_inner = new Array()
for (bc=0;bc<btnTxt.length;bc++)
{
// swap names if not counterbalancing is turned off
if (btnFlg==1)
{
//var btnNum = parseInt(ColOut[bc])
realNum=parseInt(ColOut[bc]);
if (colFix) {var txtNum = bc; }
else {var txtNum = realNum;}
}
else {
//var btnNum = parseInt(RowOut[bc])
realNum=parseInt(RowOut[bc]);
if (rowFix) {var txtNum = bc;}
else {var txtNum = realNum;}
}
if (btnState[realNum]=="1")
{
if (btnType=="radio")
{var functionstr = "onMouseOver=\"timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT type=\"radio\" name=\"mlchoice\" value=\""+btnTag[realNum]+"\" "+functionstr+">"+btnTxt[txtNum];}
else
{var functionstr = "onMouseOver=\"btnHover(this,'in');timefunction('mouseover','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\" onClick=\"recChoice('onclick','"+btnTag[realNum]+"','"+btnTxt[txtNum]+"')\" onMouseOut=\"btnHover(this,'out');timefunction('mouseout','"+btnTag[realNum]+"','"+btnTxt[realNum]+"')\"";
btn_inner[bc]="<INPUT class=\"btnStyle\" type=\"button\" name=\"" + btnTag[realNum] + "\" value=\""+btnTxt[txtNum]+"\" "+functionstr+">";}
}
else
{btn_inner[bc]=" ";}
}
for (bc=0;bc<btnTxt.length;bc++)
{
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTD = document.getElementById("btn_"+bc.toString());
}
else if (document.all)
{
//IE4/5
HandleTD=eval("document.all['"+"btn_"+bc.toString()+"']");
}
if (bc==0) {defTDcolor = HandleTD.style.backgroundColor;}
docstr=btn_inner[bc];
HandleTD.innerHTML =""; // empty for IE5 on mac bug
HandleTD.innerHTML = docstr;
}
}
// send col and row orders as events
timefunction("subject", subjtype,subjnr)
timefunction("order","col",ColOut.join("_"))
timefunction("order","row",RowOut.join("_"))
timefunction("events","open_close",evtOpen.toString()+"_"+evtClose.toString());
loaded = true; // set flag that page has been loaded;
if (tmActive) {
initTmBar();
if (tmDirectStart) {startTmBar();}
}
return;
}
function initTmBar() {
if (!tmActive) {return false;}
if (document.getElementById)
{
// IE6/NS6>/Mozilla
HandleTmCont = document.getElementById("tmCont");
HandleTmBar = document.getElementById("tmBar");
HandleTmTime = document.getElementById("tmTime");
}
else if (document.all)
{
//IE4/5
HandleTmCont =eval("document.all['tmCont']");
HandleTmBar=eval("document.all['tmBar']");
HandleTmTime=eval("document.all['tmTime']");
}
HandleTmCont.style.width=parseInt(tmWidthPx+4)+"px";
HandleTmTime.style.width=parseInt(tmWidthPx+4)+"px";
if (tmFill) {HandleTmBar.style.width="0px"; HandleTmTime.innerHTML="0 sec";}
else {HandleTmBar.style.width=parseInt(tmWidthPx)+"px"; HandleTmTime.innerHTML=parseInt(tmTotalSec)+" sec";}
if (tmShowTime) {HandleTmTime.style.visibility="visible";}
else {HandleTmTime.style.visibility="hidden";}
}
function startTmBar()
{
if (!tmActive) {return false;}
tmCurTime = 0;
tmInt = setInterval("refreshTmBar()", tmStepSec*1000);
}
function refreshTmBar()
{
if (!tmActive) {return false;}
tmCurTime= tmCurTime + tmStepSec*1000;
if (tmCurTime>tmTotalSec*1000) {clearInterval(tmInt); tmTimeUp=true; return;}
if (tmFill) {
HandleTmBar.style.width=parseInt(Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
if (tmMinLabel=="false" | tmCurTime <60000) {HandleTmTime.innerHTML=parseInt(Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var mnt = parseInt(Math.floor(tmCurTime/60000));
var secs = parseInt((tmCurTime-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
else {HandleTmBar.style.width=parseInt(tmWidthPx-Math.round(tmCurTime/(tmTotalSec*1000)*tmWidthPx))+"px";
HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" sec";
if (tmMinLabel=="false" | tmCurTime<60000) {HandleTmTime.innerHTML=parseInt(tmTotalSec-Math.round(tmCurTime/1000))+" "+tmSecLabel}
else
{ var timeleft = tmTotalSec*1000-tmCurTime;
var mnt = parseInt(Math.floor(timeleft/60000));
var secs = parseInt((timeleft-mnt*60000)/1000);
HandleTmTime.innerHTML=mnt+" "+tmMinLabel+" : "+secs+" "+tmSecLabel} ;
}
}
EDIT: There is a lot going on in that javascript function. A lot of it is exporting and importing values from and to the form. Without
really knuckling down into it, I can't be certain that my attempts
below won't ruin the integrity of your data.
Please consider hiring someone to correct this. It may be a relativeley simple change and a google of 'freelance javascript
developer' would help you find someone.
That code submits the words 'submit','submit','submit' to a function called timefunction. Apart from the hint that this code is a form of subliminal messaging to make your uses more subservient (/joke), it looks like that function is defined elsewhere. This means we cannot tell what it actually does. mlweb.js is an external javascript file that is linked at the start of this page, and that leads me to believe it is where that function is defined (that means all the code to handle that function comes from there).
There is, however, and obvious link from your submit button that calls the function using an onclick method. onClick=timefunction('submit','submit','submit') which could be replicated based on other criteria that doesn't require a click.
If, for example, you wished to make it submit the data IF someone tries to leave the page (this may cause an issue if they submit first.)
Rough code
window.onbeforeunload = timefunction('submit','submit','submit');
This code would tell the browser to send this function those three words before closing.
As that code seems to simply send text values (probably to hint timefunction to do some action in particular), there may be one of those values you could change to record that it was a close event rather than a submit. But we do not know which one without seeing the other code. I would experiment by changing one at a time if it was my code. But I would not advise you to do so since you don't know what the rest does.
Then you have an action on the form that does two things, one is onSubmit="return checkForm(this)" which seems like a form validator to make sure everything is filled in correctly. You could add this step in to ensure it has, but now you're going to try and prevent them from closing the window, and bug them about not submitting it.
Then the form is actually submitted to save.php which we also cannot see. Again, we can send the form details (as is) just as if it was submitted (WITHOUT VALIDATION). We would do that by adding document.forms["mlwebform"].submit(); with the previous code.
We can squeeze in the form validation, but I'm not sure what the return result is. Here's two options.
Like so
//no validation!!!
window.onbeforeunload = function() {
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
}
//with possible validation
window.onbeforeunload = function() {
if (checkForm(document.forms["mlwebform"])) { //if the validator returns true, continue
timefunction('submit','submit','submit');
document.forms["mlwebform"].submit();
} else { //if the validator does anything else, say so
MsgBox("Apologies, something went wrong");
}
}
This COULD work, depending on the functions in that other file. I would try the second one first, because having validation would be great. Otherwise use the first one as a fall back.
I would add this after loadMatrices(); and before </script>.
Conclusion
Seeing mlweb.js would help.
We can try and fake the same response a submit would do (this could cause errors, and we don't know how they are dealt with)
If you're brave, and there are no/little consequences to you messing up your data by dumping errors and un-validated into it through experimentation at this stage, then test out the 2 code examples above.
If the integrity of your data at this stage is important, or this is a live/production site, then don't! Get someone to properly assess the code

html text area with jquery

noob here
i got this jquery code that i found on stackoverflow
var maxLines = 2,
maxLineWidth = 5;
$('#Users_address').bind('change keyup paste drop', function() {
var value = $(this).val(),
lines = value.split('\n'),
linesLength = lines.length;
if (linesLength > maxLines) {
lines = lines.slice(0, maxLines);
linesLength = maxLines;
}
for (var i = 0; i < linesLength; i++) {
if (lines[i].length > maxLineWidth) {
lines[i] = lines[i].substring(0, maxLineWidth);
}
}
$(this).val(lines.join('\n'));
});
how would i use this with a text area??
Give your textarea an id:
<textarea id="Users_address"></textarea>
And load your script:
$(document).ready(function() {
var maxLines = 2,
maxLineWidth = 5;
$('#Users_address').bind('change keyup paste drop', function() {
var value = $(this).val(),
lines = value.split('\n'),
linesLength = lines.length;
if (linesLength > maxLines) {
lines = lines.slice(0, maxLines);
linesLength = maxLines;
}
for (var i = 0; i < linesLength; i++) {
if (lines[i].length > maxLineWidth) {
lines[i] = lines[i].substring(0, maxLineWidth);
}
}
$(this).val(lines.join('\n'));
});
});
Make your text area id 'Users_address' or change that '#Users_address' to '#{textarea-id}' replacing the stuff in the brackets with your text area id, then it will work with your text area.

delete link with js confirm + php

this was the delete link
<div class="artworkdelete">
Delete
</div>
apparently, when that link is clicked, the portal deletes the data automatically, i think it's an ajax thing because the page doesn't refresh. so i was ask to add a confirm pop up to ask the user to click yes or no if he wants to delete the data or not, and within the confirm box , it should mention the name of the data to be deleted like e.g
"are you sure you want to delete row_title ?"
here's the function of the deleteThisArtWork()
function deleteThisArtWork(artwork_id){
var artwork_id = artwork_id.split('_');
var cat_id=artwork_id[2];
artwork_id = artwork_id[1];
//$('#divStatus').html('processing request, please wait');
//$(".pleaseWait").dialog("open");
openLightBox();
$.ajax({
type: 'POST',
url: '<?php echo BASE_URL;?>ajax/ajax_methods_gallery.php',
data: 'deleteartwork=yes&artwork_id='+artwork_id+'&category_id='+cat_id,
success: function(msg){
//alert(msg);
msg = 'done';
var status=msg;
var deleted='';
if(status == 'done') {
var temp_lid = 'li_'+artwork_id+'_'+cat_id+'_';
//alert(counter);
for(var v=1;v<counter;v++){
var curid = tempIdArr[v];
curid = curid.split('#');
var curlid = curid[0];
if(temp_lid == curlid){
var del_aw_pos = curid[1];
break;
}
}
del_aw = temp_lid+'#'+del_aw_pos;
var i = 1;
var j =0;
var op = false;
var delpoint;
var endpoint;
var delcatid = '';
var artcounter = 0;
var artcounterArr = new Array();
$(".sortli").each(function (){
var atid = this.id.split('_');
//if(atid[2]!=cat_id)return;
if(this.id == del_aw){
deleted = 'yes';
delcatid = atid[2];
$(this).remove();
op = true;
i=i+1;
delpoint=i-1;
//alert('D'+delpoint);
//return;
}
if(atid[2]==cat_id){endpoint = i-1;artcounter=artcounter+1;}
else if(j==0 && artcounter > 0){
if(artcounter>0)artcounter = artcounter-1;
//else artcounterArr[j] = 0;
artcounterArr[j] = artcounter;
j=j+1;
artcounter = 0;
}
i = i + 1;
});
//alert(delpoint)
//alert(endpoint);
//alert(artcounterArr[0]);
if(op){
for(var k=delpoint; k<counter-1;k++){
var orderVal1 = tempOrderArr[k];
if(k<endpoint)document.getElementById('sortvalid_'+(k+1)).innerHTML = orderVal1;
document.getElementById('sortvalid_'+(k+1)).id = 'sortvalid_'+(k);
document.getElementById('sortdn_'+(k+1)).id = 'sortdn_'+(k);
document.getElementById('sortup_'+(k+1)).id = 'sortup_'+(k);
var t = tempIdArr[(k+1)].split('#');
t=t[0];
document.getElementById(tempIdArr[(k+1)]).id = t+'#'+k;
}
$(".rowHead").each(function (){
var taid = this.id;
var sp = this.id.split("^");
var a1 = sp[1];
//alert(a1);
//alert(cat_id);
if(parseInt(a1)>parseInt(cat_id)){
var a2 = sp[2];
var ta = 'lititle^'+a1+'^';
//alert(ta);
document.getElementById(taid).id = ta+(a2-1);
}
});
var a2temp;
var a1temp;
var delcat=null;
var rowHeadLast;
$(".rowHead").each(function (){
//var taid = this.id;
rowHeadLast = this;
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(a2temp == a2 && delcat==null){delcat = a2temp; delcatid=a1temp;}
a2temp = a2;
a1temp = a1;
});
var delok = false;
$(".rowHead").each(function (){
//var taid = this.id;
//alert(deleted);
var sp = this.id.split("^");
var a1 = sp[1];
var a2 = sp[2];
if(delcat == a2 && a1==delcatid && deleted==''){delok= true;deleted='yes';$(this).remove();}
});
//alert(delcatid);
//if(!artcounterArr[0])alert('d');
if(!delok){
$(".rowHead").each(function (){
var sp = this.id.split("^");
var cid_t = sp[1];
if(!artcounterArr[0] && delcatid == cid_t)$(this).remove();
//else if(artcounterArr[0]<=0)$(this).remove();
});
}
if(deleted ==''){
$(rowHeadLast).remove();
}
}
setDivsInArray();
//$(".pleaseWait").dialog("close");
closeLightBox();
}
else if(status == 'DBDelete:error'){
//$('#row_'+artwork_id).fadeOut(3500);
$('#divStatus').fadeIn(500);
$('#divStatus').html('<b>Artwork Delete Error</b>');
$('#divStatus').fadeOut(4500);
}
}
});
}
it's quite long , I think I don't need all of those stuff if the requirement is just delete the data when "Yes" was clicked from the confirm pop up box
now here's the delete PHP function
function deleteArtWork($artwork_id,$category_id){
$artwork_cat_lookup_del = "delete from artwork_category_lookup where artwork_id = '$artwork_id' AND category_id='$category_id'";
if(mysql_query($artwork_cat_lookup_del)){
$userObj = new User();
$allArtWorkByCat = $userObj->allArtWorkByCat($category_id);
for($itr = 0; $itr<count($allArtWorkByCat); $itr++){
$ordr = $itr + 1;
$art_id = $allArtWorkByCat[$itr]['artwork_id'];
$updateSQL = "update artwork_category_lookup set artwork_display_order='$ordr' where artwork_id = '$art_id' AND category_id = '$category_id'";
mysql_query($updateSQL);
}
$action = $userObj->userActions('Artwork id: '.$artwork_id.' is deleted', 'Gallery');
$userObj->setActionintoDB($action);
echo 'done';
}
else echo 'DBDelete:error';
return;
I don't think that you want to start changing that code above as that is used to pass the relevant data to the php script via ajax.
What you need is a javascript prompt to intercept the link click and give the user an option to continue or cancel the deletion action. Is this correct?
http://www.tizag.com/javascriptT/javascriptconfirm.php
At the start of the "deleteThisArtWork" javascript function you need to display a prompt.
function deleteThisArtWork(artwork_id){
var answer = confirm("Are you sure you want to delete this record?");
if (answer){
//do the rest of the function as usual, i.e. delete row via ajax.
}else{
return false;
}
}
That should stop the user from accidentally deleting a record without at least having to accidentally click on a confirmation popup as well!
If you want to make the text in the confirm popup dynamic, you would need to either pass in the dynamic text as a variable to the "deleteThisArtwork" method or draw it from another element on the page using some javascript.

undefined value single checkbox javascript to another page

i have two page, the first page is index.php i also using facebox framework in it. the second page is addevent.php i've tried in many ways to catch the value of single checkbox in addevent.php and passing it to index.php. but it didn't show the value. so is there someting wrong with my code ? what i'm miss ? any help would be appreciate..
index.php
echo ">".$check=$_REQUEST['check'];
echo "check[0]: ".$check[0];
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltbody>
&lta href="addevent.php" rel="facebox" &gtlink&lt/a&gt
&lt/body>
addevent.php
&lthead&gt
&ltscript src="inc/jquery-1.4.4.min.js" type="text/javascript"&gt&lt/script&gt
&ltscript src="inc/facebox.js" type="text/javascript"&gt&lt/script&gt
&ltscript language="javascript" type="text/javascript"&gt
function AddEventAgenda(){
//--- i've tried this method & firebug said:document.eventAgendaForm.checkName[0] is undefined----
var elemLength = document.eventAgendaForm.checkName.length;
if (elemLength==undefined) {
elemLength=1;
if (document.eventAgendaForm.checkName.checked) {
// we know the one and only is checked
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
} else {
for (var i = 0; i&ltelemLength; i++) {
if (eventAgendaForm.checkName[i].checked) {
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//--- also this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var len = document.eventAgendaForm.checkName.length;
if(len == undefined) len = 1;
for (i = 0; i &lt len; i++){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
var formNodes = document.eventAgendaForm.getElementsByTagName('input');
for (var i=0;i&ltformNodes.length;i++) {
/* do something with the name/value/id or checked-state of formNodes[i] */
if(document.eventAgendaForm.checkName[i].checked){
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
//--- and this one same firebug said:document.eventAgendaForm.checkName[0] is undefined---
if (typeof document.eventAgendaForm.checkName.length === 'undefined') {
/*then there is just one checkbox with the name 'user' no array*/
if (document.eventAgendaForm.checkName.checked == true )
{
var check = "&check[0]=" + document.eventAgendaForm.checkName[0].value;
}
}else{
/*then there is several checkboxs with the name 'user' making an array*/
for(var i = 0, max = document.eventAgendaForm.checkName.length; i &lt max; i++){
if (document.eventAgendaForm.checkName[i].checked == true )
{
var check = "&check["+i+"]=" + document.eventAgendaForm.checkName[i].value + check;
}
}
}
//-----------------------------------------------
window.location="index.php?tes=1" + check; // display the result
$(document).trigger('close.facebox');
}
&lt/script&gt
&ltscript type="text/javascript"&gt
// i don't know if these code have connection with checkbox or not?
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != "function") {
window.onload = func;
} else {
window.onload = function () {
oldonload();
func();
}
}
}
addLoadEvent(function () {
initChecklist();
});
function initChecklist() {
if (document.all && document.getElementById) {
// Get all unordered lists
var lists = document.getElementsByTagName("ul");
for (i = 0; i &lt lists.length; i++) {
var theList = lists[i];
// Only work with those having the class "checklist"
if (theList.className.indexOf("checklist") &gt -1) {
var labels = theList.getElementsByTagName("label");
// Assign event handlers to labels within
for (var j = 0; j &lt labels.length; j++) {
var theLabel = labels[j];
theLabel.onmouseover = function() { this.className += " hover"; };
theLabel.onmouseout = function() { this.className = this.className.replace(" hover", ""); };
}
}
}
}
}
&lt/script&gt
&lt/head&gt
&ltform name="eventAgendaForm" id="eventAgendaForm" &gt
&ltul class="checklist cl3"&gt
&ltli &gt&ltlabel for="c1"&gt
&ltinput id="checkId" name="checkName" value="1" type="checkbox" &gt
&lt/label&gt&lt/li&gt&lt/ul&gt
&ltinput class="tombol" type="button" name="Add" value="Add" onclick="AddEventAgenda()" /&gt
&lt/form&gt
why not use jQuery if you are including jQuery library?
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").val();//gets you the value regardless if checked or not
var checkbox_val=jQuery("#CHECKBOX_ID_HERE").attr("checked"); //returns checked status
or
var global_variable=""; //should be initialized outside any function
jQuery("#FORM_ID_HERE").children(":input[type='checkbox']").each(function(){
if (jQuery(this).attr("checked"))global_variable+="&"+jQuery(this).attr("name")+"="+jQuery(this).val();
});
this is just a suggestion to start from, not ideal. the ideal part is to use [] in your form.

Categories