can anyone help me store the values in my inputs to excel using PHPExcel? so far i have success storing data from my table to excel...now i wanna do is store the values in my inputs to the excel..can anyone help me please.
example of the form inputs: enter image description here
i want is all the data in my form will be stored in excel....my code is not working help me please.
current code:
<?php
if (!isset($_POST['send'])) { ?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<?php } else {
require_once 'Classes\PHPExcel\IOFactory.php';
$filename = 'file.xlsx';
$title = $_POST['title'];
mysql_connect("localhost","root","") or die ("cant connect!");
mysql_select_db("test") or die ("cant find database!");
$objReader = PHPExcel_IOFactory::createReader('Excel2007');
$objReader->setReadDataOnly(true);
$objPHPExcel = $objReader->load($filename);
$objWorksheet = $objPHPExcel->getActiveSheet();
$objWorksheet = $objPHPExcel->setActiveSheetIndex(0);
$name1 = $_POST['name1'];
$optA1 = $_POST['optA1'];
$optB1 = $_POST['optB1'];
$optC1 = $_POST['optC1'];
$optD1 = $_POST['optD1'];
$total1 = $_POST['total1'];
$remarks1 = $_POST['remarks1'];
$name2 = $_POST['name2'];
$optA2 = $_POST['optA2'];
$optB2 = $_POST['optB2'];
$optC2 = $_POST['optC2'];
$optD2 = $_POST['optD2'];
$total2 = $_POST['total2'];
$remarks2 = $_POST['remarks2'];
$result = array(
'$name1',
'$optA1',
'$optB1',
'$optC1',
'$optD1',
'$total1',
'$remarks1'
),('$name2',
'$optA2',
'$optB2',
'$optC2',
'$optD2',
'$total2',
'$remarks2');
if(isset($_POST['send'])){
$headings = array(
'NAME',
'Gen Info. & Technical Knowledge',
'Communication Ability',
'Attitude Towards Profession',
'Appearance',
'TOTAL',
'Remarks'
);
$points = array(
' ',
'(3 pts)',
'(3 pts)',
'(2 pts)',
'(2 pts)',
'(10 pts)',
' '
);
$objPHPExcel->getActiveSheet()->getColumnDimension('A')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('B')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('C')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('D')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('E')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('F')->setAutoSize(true);
$objPHPExcel->getActiveSheet()->getColumnDimension('G')->setAutoSize(true);
$objPHPExcel->getActiveSheet()
->getStyle('A1:I15')
->getAlignment()
->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$objPHPExcel->getActiveSheet()->getStyle('A1:I1')->applyFromArray(
array(
'font' => array(
'bold' => true
),
'alignment' => array(
'horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,
),
'borders' => array(
'top' => array(
'style' => PHPExcel_Style_Border::BORDER_THIN
)
),
'fill' => array(
'type' => PHPExcel_Style_Fill::FILL_GRADIENT_LINEAR,
'rotation' => 90,
'startcolor' => array(
'argb' => 'FFA0A0A0'
),
'endcolor' => array(
'argb' => 'FFFFFFFF'
)
)
)
);
$objPHPExcel->getActiveSheet()->fromArray($headings, null, 'A1');
$objPHPExcel->getActiveSheet()->fromArray($points, null, 'A2');
$row = 3;
while( $rows = mysql_fetch_row($result)){
$objPHPExcel->getActiveSheet()->fromArray($rows, null, 'A' . $row);
$row++;
}
}
header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
header('Content-Disposition: attachment;filename="'.$title.'.xlsx"');
header('Cache-Control: max-age=0');
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save('php://output');
}
if (!isset($_POST['send'])) { ?>
<form id="form1" name="form1" method="post" action="" >
FILE TITLE: <input name="title" type="text" id="title" />
<table>
<td><input name="name1" type="text" value="" required size="41" id="query1" /></td>
<td>
<input id="textboxid" type="radio" name="optA1" value="1" />1
<input id="textboxid" type="radio" name="optA1" value="2" />2
<input id="textboxid" type="radio" name="optA1" value="3" />3
</td>
<td>
<input id="textboxid" type="radio" name="optB1" value="1" />1
<input id="textboxid" type="radio" name="optB1" value="2" />2
<input id="textboxid" type="radio" name="optB1" value="3" />3
</td>
<td>
<input id="textboxid" type="radio" name="optC1" value="1" />1
<input id="textboxid" type="radio" name="optC1" value="2" />2
</td>
<td>
<input id="textboxid" type="radio" name="optD1" value="1" />1
<input id="textboxid" type="radio" name="optD1" value="2" />2
</td>
<td><input type="text" name="total1" size="3" /></td>
<td><input name="remarks1" type="text" value="" required size="8" /></td>
</tr>
<tr>
<td><input name="name2" type="text" value="" required size="41" id="query2" /></td>
<td>
<input id="textboxid" type="radio" name="optA2" value="1" />1
<input id="textboxid" type="radio" name="optA2" value="2" />2
<input id="textboxid" type="radio" name="optA2" value="3" />3
</td>
<td>
<input id="textboxid" type="radio" name="optB2" value="1" />1
<input id="textboxid" type="radio" name="optB2" value="2" />2
<input id="textboxid" type="radio" name="optB2" value="3" />3
</td>
<td>
<input id="textboxid" type="radio" name="optC2" value="1" />1
<input id="textboxid" type="radio" name="optC2" value="2" />2
</td>
<td>
<input id="textboxid" type="radio" name="optD2" value="1" />1
<input id="textboxid" type="radio" name="optD2" value="2" />2
</td>
<td><input type="text" name="total2" id="total2" size="3" /></td>
<td><input name="remarks2" type="text" value="" required size="8" /></td>
</tr>
</table>
<input type="submit" name="send" value="send to excel" id="send" formnovalidate />
</form>
</body>
</html>
<?php }
error:
<br />
<b>Warning</b>: mysql_fetch_row() expects parameter 1 to be resource, array given in <b>C:\xampp\htdocs\test\index.php</b> on line <b>114</b><br />
PK ܃KD%¸õºa [Content_Types].xmlÍ”]KÃ0…ïý%·Òf› "ëváôRΓ·kXš„¼Ù׿÷m»©+Žô¦¡4ç<§'ãé®2Éjgs6Ì,+Òv™³·ÅSzÇŒÂ*aœ…œíÙtr5^ì=`Bb‹9+cô÷œ£,¡˜9–¾.T"ÒkXr/äJ,ƒ[.`ck6¿?hÉ\„ø,*Âðá‘Ü }3òcÉC+¬Ù9Þ-E¤à|cÕjêŠBKPN®+’dÍuíÂO1î
`oú Ba +“µ¦Gò
±61yÜ‘{Ûy ƒçñef¤læ`©}¡û‡Në6=‹ ý,ˆ-m¥ŽÒ·.¬Þ[]ºözÌ*¡m×¢“xœGN¨Þ nNJ=YBˆúkÙ;ÙÒ8~ܵú—ÄCÛM5È›axáÚ?ýÏÌ1ú'9nþ(–"€zËÅo ïÞǼ¹À'PK ܃KD¶78é K _rels/.rels’ÍjÃ0€ï{
£{£´…1F^Ê ·2²Ðlå‡$–±½-}ûy‡±ºÒÃŽ–¥OŸ„vûyÕ;‡Ø‹Ó°.JPìŒØÞµ^ê§Õ¨˜ÈYű†3GØWw»g)åšØõ>ªqQC—’DŒ¦ã‰b!ž]þi$L”ò3´èÉÔ2nÊòÃoT¦:Z
áh· ê³ç[ØÒ4½áƒ˜·‰]ºÐyNì,Û•¹>¤>£j
-'
VÌ)‡#’÷EF^6ÚÜnô÷´8q"K‰ÐHàë>_ׄÖÿ¹¢eÆÍ<⇄áUdøvÁÅ
TŸPK ܃KDxÔÙ÷ Ó xl/_rels/workbook.xml.rels½“ÍjÃ0„ï}
±÷X¶Ó†R"çR
¹¶îim™Ø’¶?~ûª
m¦““˜;ó1BÛÝçгw±sV#‘åÀÐ*§;Û
xŸV÷À"I«eï,
1®ºÙ>c/)íDÓùÈ’‰‘à<*ƒƒŒ™óhÓMã )ÉÐr/ÕA¶ÈË<ßð0õ€êÌ“íµ€°×°zôøo×4ÂG§Þ´t!‚GûÄÏjZ$G%à—ãË%ã)íâ)ýG‡ÅÃzÑ
Œ¨_(¤ž61ÏÁÜ. óáÂ!D:ü¾QÓ1ÛÌÝ•aÊ9˜Í•aÖ¿0üì/V_PK ܃KD5‰À‰ Y docProps/app.xmlSÁnÛ0½ï+Ý9I1¬bH7ôÐb’vgN¦c¡²dˆ¬‘ôë';ˆë´Ûe:=ñ=<<’’º=4.ë0’
¾óY.2ô&”Öïñ´ûqu#2bð%¸à±G$q«¿¨M-F¶HYrðTˆš¹]II¦Æh–hŸ˜*Ä8]ã^†ª²ï‚ymг\äùW‰F_byÕŽ†âä¸êøMË`ú|ô¼;¶ÉO«omë¬NMêGkb Pqöý`Ð)9%U2Ú¢y–:WrzU[×ÉXWà•|/¨{„~f°‘´êxÕ¡á3²oij‘ýÂ>N!:ˆ<‹“ìt°k‰£þâÕˆLJŽÅNµSl¯õr$p)”c„/#î,;¤ŸÕ"ÿ%ñršxÈ &·}¾ù4ß%µø7µüÔÕ9߇DëдàÓØåˆÁÃ{투¡§vî€ñ¼—Ë¢ÚÖ±L«÷6Ô}j0º^¿®Áï±<k>ý+z>ý=_Ìòt†Çs®)ùþ)ôPK ܃KD~cJp ï docProps/core.xml}RANÃ0¼óŠÈ×*± ‚(M%#œ#B¢®Æ^ZÓĶì…ßã$mÚ Bòa×3X~ÕUô Î+£$M‰##•^/ÈÓê6¾ ‘G®%¯Œ†iÁ“eyR›ãàÁø(iŸ» D›SêÅjî“ÀÐ|3®æZ·¦–‹-_Í›ÓKŽœv‚±ÉNRŠQÒ~¸ª‚B5hô4MRzà"¸Úÿù GŽ˜µÂÖŸÔ=8²¿¼‰MÓ$ÍiO
ó§ôåþî±·+ÝE%€”…¹pÀѸò©BœCA.» +îñ>Dý¦#^µG¼ßX±36¼…òaü=ò|z}³º%e—iÌ.ãt¾bYÎX8³¾èþŸˆTëÝOÿʦg1Ëbv¾ÊÒü|žgÙŒ¥Ù½JïVPöžwe¨$xá”Å°l4¹½ÿx}86!-´qÒ—}:‡®ÛÃàem\;#?ºÉŽ–ßPK ܃KDs‘{Y³ ¦ xl/theme/theme1.xmlíYOoÛ6¿ïSº·²lÉu‚:EìØëÖ¦
·C´DK¬)Q 餾
íqÀ€aÝ°Ë€Ýv¶h]ºO“ÃÖý
{úc‹Šé6iSlCëƒ-’¿÷ŸïñQ¾|å^ÌÐ!’ò¤k9"‰Ïš„]ëÖhx¡c!©p`ÆÒµæDZW¶>¸Œ7UDb‚€<‘›¸kEJ¥›¶-}˜Æò"OIk.b¬`(B;øØÆÌn6m;Æ4±P‚càzs2¡>A£Œ¥µµ`>`ð•(™MøLø¹D"ÇS'û‘sÙgbÖµ#NÀFäž²ÃRÁB×jäËÞºl/‰˜ZC«Ñ
óOIWÓfN'Âñ’к—v–ü›ÿUÜ`0èœ%¿€},uV°î°ãô<5Pñ¸Ê»ßðn¯ñoà7z½ž·Q÷*¼»‚ï4Úîv³†w+¼·ªo»ßo×ð^…o¯à‡—6ÚnŸƒ"F“é
:‹ç22KÈ„³«FxàŨP¶¶»
úDÛk1¾ËÅ yp±¢ Ró”L°¸>ŽÇ‚âL Þ$X[)¦|¹2•ÉBÒ4U]ëãCFTO|ñô1zñôÑñý'Ç÷9~ðàøþÏ«8 uÂçßñ÷·Ÿ¢¿÷üáWf¼Ôñ¿ÿôÙo¿~i*øìëG<yôì›Ïÿü᡾-ðX‡hL$ºAŽÐ>Á6ƒ 2g£E˜Ö(pHp ¢ðÆ3®Gêλ- ˜€ÎîÖt=ˆÄLQðZ×€»œ³Fs®e²tsfIh.f:nãC“ìþ‰Ðf)ìdjbÙHMÍ=ÑÆ!IˆBÙŸb »Ciͯ»Ô\ò‰Bw(êajtɈŽ•™è*!.sluÍ7»·Q3ûrXGBB`fbIXÍâ™Â±Qc3y«È¤äÁ\ø5‡K‘ ãh)M47ż¦î5•Èö]6ëH¡èÔ„¼Ž9ב;|Úpœu¦I¤c?’SØ¢íqeT‚×3$Cp²6Ü·)QgKë[4ŒÌ$[™ SJ^ÏÇ9›`’”õ½V©cš¼¬l3
uû}Ù^À·ác§(Öëpÿýƒgɬx_¡ßWèw±B¯Ëåó¯ËU)¶õ^;g¯m¼'”±5gäºÌ‹¸ó‚!L惜hÙç§<–âj¸Pàü ®>¡*:ˆp
bœ\B(KÖ¡D)—p»°Öòί¨lÎç¼Å½ÐXíò ˜né÷Í%›|J]P+cpZaKo&Ì)€§”æxfiÞK¥Ùš7!oÎ^&8íf!6
f$Èü^0X„åÜC$#2FŽÑ§uJ·u^í5MÚFëͤ&Hº8w8ï¢ÔX‰’½šŽ,©Ðhå5=ù8íZè¹à1NŸÌJfaÒµ|UšòÊd>i°y[:µ×D¤Bª,£‚*_Z¼ŽI*ý›ž›ùá|°_W‹VÇùµ°O†–L&ÄWkfªa¹ÆgŠˆƒ(8Bc6ûôv‹ÝP GEs1¡n¹ñê™_fÁÉ×>ev`–F¸¬I-ö<^ê4õì5º¿¦)s4Å{wMÉv.4¸ ¿zA 0Êöh×âBEªPQ( qÈe^Ò"S ±ìv¦+9¬êVÁ£(ra¤öiˆ…J§"AÈž*í|3§©Ÿ¯FeYª+ÓâwL eÙÛÎì·P´¨&¥#rÜÉ Ù¦ì‡Ãÿpçã6^§=¨¹géE\èkGÁÆ›©pÆ£¶i¶¸éú¨Máš‚²/(ÜTø¬êoG|¢–%‚x¡S¦ßrr:w4ã2Vo·ªBÐi¼ýæSsvk³·ãlÏàkï家WSÔÖ.2ùhåÏ,>¾²wà~4cJïîÁ¥´¿øøØéÖ?PK ܃KD ™äÀ, K xl/sharedStrings.xmlm’ÍNÃ0„ï<…å‚uZ¤
•$UPJ"À$ÛÆ"þÁ»iéÛ×”ô¸Ÿg¼šÑÆó_Ý°xTÖ$|<Š8SÚJ™mÂ?‹Ç«Î¤©dc
$ü ÈçéYŒH,X
&¼&r3!°¬AKY&¼l¬×’Âè·Ya
#º“(š
-•á¬5꧅ܶ†Âò)OcTiLé[öúJcÑÍl†-ÍƎعÔî–PÖF•²a+c÷
T[è[r«uÛi(¤cÙ—jú¢ŒHQ[+ì^ú
Ù»·À®Ô9^šr°©XÙK~„>ü7~Yæ}t—ùS¾¾ï‡î*ž¡“eh>tˆàwÀSÖ·_\3Gx9À“Óxä«FhzrÀž%þŠp
éPK ܃KDwÀT;z É
xl/styles.xmlíVMoœ0½÷WX¾7àR5¥‘zhT5[©WkÅØÈ6ÛÝüúúƒÏMVí)í!p`æyüÞŒ±’›CËÑ”fR¤˜\Ä(eÅD“âÛüý'Œ´¡¢¢\
Hñ4¾ÉÞ%Ú9<ì ²×º£¥íhP{À:Å;cºë(ÒåZª/dÂŽÔRµÔXW5‘¶sh¥SË£MŒZÊÎÑ·yk4*e/LŠceI-ÅŒlp ²¤#{ʇ¶°µQì#lakñãOÁ'Äy¥äR!Õ)ÎóØ_´(î(g…bŒ‚ðJž¼º¼h›ã|Z–8 YÒQc#‰Ü:h°·Çæ¢÷‡èFÑ#Ù\:Úæn™d¸Q±˜³¬'z–¶b Œ4^‰3TaTA£ÀúW1v«(;ÔI͌ߣZ-Õmìn/æBŸM §æ´‡ Ñ2•)Kÿ°‹[HUÙ²ÜuŠF#Kœ¢?)6;¿{ϼÍ(Žóê”ÀùƒcøYOR.óCÂAøR¹Ú‘{ã£ióÌ#§²dÜÚË#{¨ŸS®¥^æG´ëø1—áPï¾oP¹?׋K0{Ÿ=ÇìßrÖˆM–ÐÑE;©Ø“¥w{¾Šrìz”a¥ƒ
iŒl12p0ߥ¡ã¶#¿í¶LqM¹¶MHï[™³ s‹s¨ÿ·úÉÙúK€z•òÉ™ò7Ëòɪ|òå““òÉ[ùoåÿÓò£¡.šîªåN(rßÞß»ÊlšÖ¬è7L¼Ðn-gu¨×ÿ,†öW)¨TPÓž›í¥x¶¿BÅúö
QßØ^š!ÊÛs(¾^ãOXöPK ܃KDÙ|÷5¬ xl/workbook.xmlQËn1¼÷+Ý›];¶Ñ^hÓ´úBã¤gyÅÍÑ¢ÖNòõ¥ä8Ý 9ôD‘Ž8ÃÕÙ½5b‘лFNNj)Àµ^£»mäõæâí;)()§•ñù $ÏÖoV{ï¶Þß ž_RP-÷B‚¸™‹ŽÙ§–UEmVщà¸ÓùhUâ4ÞVÄ3JS¬©¦u½¨¬B÷Ä°ŒÿÃá»[8÷í`Á¥I£K¢ÉõªC7•B…ð]YÞ÷ÞHa¥OèFÎ8õ{xQˆCø0 ÉɼžËjý¬ügì¨6=Òï§Fåxƒ°§¿øœ
Õ&ÜÁFmÉN«!ù4 â¹Jð9ú!ß'Rt)]e_
Ò¢C‹y)Ψ÷û/>â£wI™«6zcÊTn”!þž+,<aû˜ÔöW6¨‘‹š wH¸Eƒé¡‘åm «¨F2ÊŽQ¸¢º|U>áx©s\"?⥞e†ÐÓz:BÏ_EŸŽÐ§#ô¢lw\IC‡t¾q•¶ù8ÊNÓÙ|ò^–ü¬‘Ùvvx0æ#×~¸¯^_3çñZë?PK ܃KD§êçm: M xl/worksheets/sheet1.xml˜]“¢8†ï÷WPܯ~t©SÓ*BÕlÍT÷ÌÎuZ¢f ¢Nï¯ß!éݾéNÞsòæÉ! döé×1±ÎT䌧s
Û¢é–Ç,ÝÏí߃ß'¶•K’Æ$á)Ûo4·?-~›]¸xÍ”JK<äÙª`&hNÅ™ÚZLó¹}2{óíI>àMUdÇÅ‘HÕûa®Æ¸p:&C×qFÃ#aiåð þ‹ßíØ–®øöt¤©,MMˆTkÊ,ËíŬ˜á›XÌøI&,¥ß„•ŸŽG"ÞiÂ/jéöUxbûƒÔÂp1Öãb¦Ìu•,Awsû3zˆ¯SŠŒ?½ä¶%ÉË3MèVÒ¸ðÖõzáüU#%©:ç~ÙQ8ªVRœh)>ñË’'¡ª‹º.z´2.¼ôìDý;Ó%M’¹iè¿ž¨«çh¶¯`AQ3µò˜îÈ)‘jžV‹Ål[Um¾Ð3MžtQœ¶¦¨´¦&Úò$/þZG–<’_åBY,sÛL|Œ<Ûz¡¹˜¼.p{Ê%?þ,³ª5Ë·„ÞŒKK·²tkKo<;¾3ž|ØÓ«<½ÚÓÕœÎä㘸²Ä7Lw0¢)þ¸§_yúµ'r&vüaÏQå9ºy:4™à—s\yŽkÏéÀxÿ¯å°ÜOÅ.]I3Á/–(ïÊŒèG z˜ªû`«ÅÏZ-v†ò×7÷yá̆gmSe<–^#µ3–0Ãmg¬`†×ÎXÃÜÎ`†ßÎØÀŒQ;#„ãvFTfàFƤΪJÖåt;ËéÃQcøÔ('Ì#Fŗ溺:RŒ«²~?%èH1®Üæ݅׌Žë5c¨»Ž^g½æ#ûуØÆvZ6ÇiÕ[÷Ä‚žØ¦'zE(ÔŒyÝÂÂMScõÈ€ZâΉËõÄÖ=± '¶é‰…=±wî®VüÎùÍ«ôaŒ‡ÉÒ¿¿W=±uO,è‰mzb¡wEþû·Ø¨³#£jàðZSXšÂÊÖ¦˜ÂÆBSˆB‹zÜI=6©Mai
+SX›B`
SM!ß¡žtROLjSXšÂÊÖ¦˜ÂÆBSˆ&w¨§ÔS“Ú–¦°2…µ)¦°1…Тéjät¿Ò8&7P–#Ye
” ( „#‰šJ›ÿÎ+üð#À ?üð#À ?ºÇßý„\Àï~ð»€ßü.àw¿øÝ{üÝïÈüà÷ ¿ø=Àï~ð{€ß»Çßýj€0àÇ€~ø1àÇ€~øñ=þî_nä~ðû€ßü>à÷¿ø}Àï›üÃÆ×UuªÁeu¨PôçöŽ$¹ú2ã/)=¯ûù–¦D0~SÊÓ}4žœŽ©©>ñËMbiNH,ÕŽÄð-£"aéë-Ó„Jj:”jË¡<6ù·¯4nÓæ\ÜLN’,‘TÔRÆÎ\~'/ 5Ý~¤ ôSUÎKå׬8t²ö·sjp<ÓëW±Döô"öj©VBw*âÔ¯´(OeŠ¶äYÑRô…Kõ}íŠ"Ýót¹¼v*_5Ñ)³2¢Ê÷Ìþ¡Å«#Œ¦²8›ÛÕ1¾ÀDŠ#G=ôwL~çõ±PÕ¯>Ü‹ÝTNóY1Ûí¨P–_ãx}¦éíb\¹ll%5ÓO&+¾½„íSU…¨ôÅŒÇqy¦6o£šåì¥|mS5}Þìèv= ÙÙi´zH«WtêAí^³ ª[Ÿ„.þPK ܃KDÂ+ÿ ™ xl/worksheets/sheet2.xmlTÉrÛ0½÷+4¼×rÚtåLšÖMgÒI&Ks¦EÈbM* ÙM¿¾ µ:é¡'Äðhyö»2Éœ×h3q2›‹lŽJÛm&îׯ?ŠÄ“´J´‰'ðâlõjy#·ó% %L°ðµÌù°vàÁíAÐúL”Dõ"M}^B%ýk°|R «$±ë¶©ç©"SeÒ7óùû´’Úv÷?X:‡Ï˜7XjIIÜ“/uíÅj3ܸÕ2ÚÂK|SUÒ=}ƒn]ôÀÞ–€tµL‡8¥™<¨”8(2q~²87â…~b'$7w` 'P™`Mƒ\Ä]8üÖB¾ÄÃW§ÕWÃR‘k oñpæ’eág u0qä
É%öpÆ„8àWWÎXmÈ1µûÂÖQ2n\A!Cœçº^Og§"餹‚=˜Û ÉüãªÖ7ýY’Le‘º
£Ÿ‰BÏ
áæ'ã~ð}V:#Ò¾dè膦©ìs”+!myà^\lÑ\¼|ªÁq?»ñ#±´ÏZôˆ¡}ƒ+Ìw Ž«õèƆeC¸Ö†À
P÷H÷rcà9Ûƒ5/ùXÓÚiK×uàd;I< wAé89!Hná»t[n51PðÉ|öA$®}âhÖÑz'’
aÕ{eœ¶à½
:#õNÇˉš:©%Ëw§ÿ#\tš×-nY&º™
,M8Ÿóðšîq˜±ÎÔŠÊn½Ú´ë˜/Qº(À1åµR_ö`ÇÇèÖÚyšŒgzÔTòæ÷û#ÞÚ€uBt8¯½RíFñfLl6Ûì-ÜÛ<ív¸>u‚=L"”6„yÑ‚Ž½© ìÕÕ_PK ܃KDÂ+ÿ ™ xl/worksheets/sheet3.xmlTÉrÛ0½÷+4¼×rÚtåLšÖMgÒI&Ks¦EÈbM* ÙM¿¾ µ:é¡'Äðhyö»2Éœ×h3q2›‹lŽJÛm&îׯ?ŠÄ“´J´‰'ðâlõjy#·ó% %L°ðµÌù°vàÁíAÐúL”Dõ"M}^B%ýk°|R «$±ë¶©ç©"SeÒ7óùû´’Úv÷?X:‡Ï˜7XjIIÜ“/uíÅj3ܸÕ2ÚÂK|SUÒ=}ƒn]ôÀÞ–€tµL‡8¥™<¨”8(2q~²87â…~b'$7w` 'P™`Mƒ\Ä]8üÖB¾ÄÃW§ÕWÃR‘k oñpæ’eág u0qä
É%öpÆ„8àWWÎXmÈ1µûÂÖQ2n\A!Cœçº^Og§"餹‚=˜Û ÉüãªÖ7ýY’Le‘º
£Ÿ‰BÏ
áæ'ã~ð}V:#Ò¾dè膦©ìs”+!myà^\lÑ\¼|ªÁq?»ñ#±´ÏZôˆ¡}ƒ+Ìw Ž«õèƆeC¸Ö†À
P÷H÷rcà9Ûƒ5/ùXÓÚiK×uàd;I< wAé89!Hná»t[n51PðÉ|öA$®}âhÖÑz'’
aÕ{eœ¶à½
:#õNÇˉš:©%Ëw§ÿ#\tš×-nY&º™
,M8Ÿóðšîq˜±ÎÔŠÊn½Ú´ë˜/Qº(À1åµR_ö`ÇÇèÖÚyšŒgzÔTòæ÷û#ÞÚ€uBt8¯½RíFñfLl6Ûì-ÜÛ<ív¸>u‚=L"”6„yÑ‚Ž½© ìÕÕ_PK ܃KDÍKR"x # xl/worksheets/_rels/sheet1.xml.relsMŒ1! {_A¶÷#cÌq×ù £Øp+a!,1ú{)-'“™yýä¤ÞÔ$¶p˜(bW¶ÈÞÂã~ÝŸAIGÞ0&_X—Ý|£„}4b5&,Bïõ¢µ¸#e*•x˜giûÀæuE÷BOúhÌI·ÿèåPK ܃KDÍKR"x # xl/worksheets/_rels/sheet2.xml.relsMŒ1! {_A¶÷#cÌq×ù £Øp+a!,1ú{)-'“™yýä¤ÞÔ$¶p˜(bW¶ÈÞÂã~ÝŸAIGÞ0&_X—Ý|£„}4b5&,Bïõ¢µ¸#e*•x˜giûÀæuE÷BOúhÌI·ÿèåPK ܃KDÍKR"x # xl/worksheets/_rels/sheet3.xml.relsMŒ1! {_A¶÷#cÌq×ù £Øp+a!,1ú{)-'“™yýä¤ÞÔ$¶p˜(bW¶ÈÞÂã~ÝŸAIGÞ0&_X—Ý|£„}4b5&,Bïõ¢µ¸#e*•x˜giûÀæuE÷BOúhÌI·ÿèåPK ܃KD%¸õºa [Content_Types].xmlPK ܃KD¶78é K ’ _rels/.relsPK ܃KDxÔÙ÷ Ó ¤ xl/_rels/workbook.xml.relsPK ܃KD5‰À‰ Y Ó docProps/app.xmlPK ܃KD~cJp ï Š docProps/core.xmlPK ܃KDs‘{Y³ ¦ ) xl/theme/theme1.xmlPK ܃KD ™äÀ, K
xl/sharedStrings.xmlPK ܃KDwÀT;z É
k xl/styles.xmlPK ܃KDÙ|÷5¬ xl/workbook.xmlPK ܃KD§êçm: M é xl/worksheets/sheet1.xmlPK ܃KDÂ+ÿ ™ Y xl/worksheets/sheet2.xmlPK ܃KDÂ+ÿ ™ xl/worksheets/sheet3.xmlPK ܃KDÍKR"x # à xl/worksheets/_rels/sheet1.xml.relsPK ܃KDÍKR"x # | xl/worksheets/_rels/sheet2.xml.relsPK ܃KDÍKR"x # 5 xl/worksheets/_rels/sheet3.xml.relsPK ÿ î
Perhaps if you defined your array as
$result = array(
array(
$name1,
$optA1,
$optB1,
$optC1,
$optD1,
$total1,
$remarks1
),
array(
$name2,
$optA2,
$optB2,
$optC2,
$optD2,
$total2,
$remarks2
)
);
rather than as an array of string values with syntax errors
This really is basic PHP syntax, that you should be able to debug yourself
EDIT
You're also using while( $rows = mysql_fetch_row($result)){ without any database access whatsoever because you're trying to read the rows of data from the array, not from a database. Change it to:
foreach($result as $rows){
to just iterate over the array
Related
when the checkbox is checked by the user, I want to push the value(the numerical value are in the JS) for the checked box in an array, get the sum and display the total calories in the alert message.
here's my code so far:
var rice = 204;
var bread = 140;
var chicken = 147;
var beef = 282;
var carrots = 150;
var beans = 70;
function myFunction() {
var rice = document.getElementById("rice");
var bread = document.getElementById("bread");
var chicken = document.getElementById("chicken");
var beef = document.getElementById("beef");
var carrots = document.getElementById("carrots");
var beans = document.getElementById("beans");
const food = [];
if (rice.checked == true) {
food.push(window.rice);
} else if (bread.checked == true) {
food.push(window.bread);
} else if (chicken.checked == true) {
food.push(window.chicken);
} else if (beef.checked == true) {
food.push(window.beef);
} else if (carrots.checked == true) {
food.push(window.carrots);
} else if (beans.checked == true) {
food.push(window.beans);
}
let sum = food.reduce(function(a, b) {
return a + b;
}, 0);
console.log(sum); /*sum of array not working */
console.log(food);
}
myFunction();
<form>
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
<script src="try.js"></script>
the values is not appending in the array when i check multuple boxes. it only appends the first box that i checked and doesn't include the next boxes. i cant get the sum, how can i fix that?
You can do this way
document.querySelector('form').addEventListener('click', e => {
if (e.target.matches('input[type="radio"]')) {
const checked = document.querySelector('#vegetarian').checked;
document.querySelectorAll('.meat').forEach(chk => {
chk.disabled = checked;
chk.checked = false;
});
}
});
const calories = {
rice: 204,
bread: 140,
chicken: 147,
beef: 282,
carrots: 150,
beans: 70
};
function myFunction() {
const food = [];
const veg = [];
let sum = 0;
document.querySelectorAll('input[type="checkbox"]').forEach(chk => {
if (chk.checked) {
food.push(chk.value);
if (chk.classList.contains('veg')) {
veg.push(chk.value);
}
sum += (calories[chk.value] || 0);
}
});
console.log(sum); /*sum of array not working */
alert(food);
if (veg.length < 2) {
alert('two vegs are recommendeded');
}
}
<!DOCTYPE html>
<html>
<head>
<title>Meal Plan</title>
</head>
<body>
<form onsubmit="return false;">
<h2>Meal Plan</h2>
<h3>Dietary restrictions:</h3>
<input type="radio" name="diet" id="none" value="none" required>
<label for="none">None</label>
<br/><input type="radio" name="diet" id="vegetarian" value="vegetarian" required>
<label for="vegetarian">Vegetarian</label>
<br/><input type="radio" name="diet" id="lowcarb" value="lowcarb" required>
<label for="lowcarb">Low Carb</label>
<br />
<h3>Food items:</h3>
<input type="checkbox" name="Rice" id="rice" value="rice">
<label for="rice">Rice</label>
<br /><input type="checkbox" name="Beef" class="meat" id="beef" value="beef">
<label for="beef">Beef</label>
<br /><input type="checkbox" name="Bread" id="bread" value="bread">
<label for="bread">Bread</label>
<br /><input type="checkbox" name="Beans" class="veg" id="beans" value="beans">
<label for="beans">Beans</label>
<br /><input type="checkbox" name="Chicken" class="meat" id="chicken" value="chicken">
<label for="chicken">Chicken</label>
<br /><input type="checkbox" name="Carrots" class="veg" id="carrots" value="carrots">
<label for="carrots">Carrots</label>
<br /><br /><input type="submit" onclick="myFunction()" />
</form>
</body>
</html>
Your existing if ... else if ... block got problem, it won't run the rest of else if once a condition is true.
do that this way ... (less code and more readability)
const
myForm = document.forms['my-form']
, calories =
{ rice : 204
, bread : 140
, chicken : 147
, beef : 282
, carrots : 150
, beans : 70
}
, NotVegetarianFood = ['beef', 'chicken' ]
;
myForm.oninput = e =>
{
if ( e.target.name === 'diet' )
{
let isVegetarian = (myForm.diet.value === 'vegetarian')
NotVegetarianFood.forEach( food =>
{
myForm[food].disabled = isVegetarian
if (isVegetarian)
myForm[food].checked = false
})
}
}
myForm.onsubmit = e =>
{
e.preventDefault()
let
sum = 0
, vegetables = 0
, formValues =
Array
.from(new FormData(myForm).entries() )
.reduce((res,[food,_])=>
{
if (!!calories[food])
{
vegetables += NotVegetarianFood.includes(food) ? 0 : 1
sum += calories[food]
res.push (food)
}
return res
},[])
myForm.message.textContent = (vegetables > 2)
? ''
: '2 vegetables options are recommended for a healthy meal regardless of the dietary restrictions.'
console.clear()
console.log( JSON.stringify( formValues), '\n-- calories sum =', sum )
}
fieldset {
width : 16em;
margin-bottom : .7em;
}
legend {
font-weight : bold;
}
label {
display : block;
margin-top : .4em;
}
<form name="my-form">
<h3>Meal Plan</h3>
<fieldset>
<legend>Dietary restrictions:</legend>
<label> <input type="radio" name="diet" value="none" checked > None </label>
<label> <input type="radio" name="diet" value="vegetarian" > vegetarian </label>
<label> <input type="radio" name="diet" value="lowcarb" > Low Carb </label>
</fieldset>
<fieldset>
<legend>Food items:</legend>
<label> <input type="checkbox" name="rice" > Rice </label>
<label> <input type="checkbox" name="beef" > Beef </label>
<label> <input type="checkbox" name="bread" > Bread </label>
<label> <input type="checkbox" name="beans" > Beans </label>
<label> <input type="checkbox" name="chicken" > Chicken </label>
<label> <input type="checkbox" name="carrots" > Carrots </label>
</fieldset>
<button type="submit">submit</button>
<output name="message"></output>
</form>
I am working with dynamic text boxes.
I want to add the data that is entered in the text boxes to my database.
My markup:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).on('click', '#add_row', function(){
count++;
$('#total_item').val(count);
var html_code = '';
html_code += '<input type="text" placeholder="Number '+count+'" name="number[]" id="number'+count+'" data-srno="'+count+'" /><br />';
html_code += '<input type="text" placeholder="Name '+count+'" name="name[]" id="name'+count+'" data-srno="'+count+'" /><br />';
html_code += '<input type="text" placeholder="Price '+count+'" name="price[]" id="price'+count+'" data-srno="'+count+'" /><br />';
html_code += '<button type="button" name="remove_row" id="'+count+'" class="btn btn-danger btn-xs remove_row">X</button><br />';
});
</script>
<button type="submit" class="btn btn-primary" name="send">Save</button>
</form>
Which results in the following document fragment:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="number[]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="name[]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="price[]" id="price1" value="10" placeholder="Price 1" /> <br />
<input type="text" name="number[]" id="number2" value="12" placeholder="Number 2" /> <br />
<input type="text" name="name[]" id="name2" value="bbbb" placeholder="Name 2" /> <br />
<input type="text" name="price[]" id="price2" value="15" placeholder="Price 2" /> <br />
<input type="text" name="number[]" id="number3" value="38" placeholder="Number 3" /> <br />
<input type="text" name="name[]" id="name3" value="cccc" placeholder="Name 3" /> <br />
<input type="text" name="price[]" id="price3" value="29" placeholder="Price 3" /> <br />
<button type="submit" class="btn btn-primary" name="send">Save</button>
</form>
When submitting the form I want to add the following data to the database:
| session_id | number | name | price |
|-------------|----------|----------|----------|
| 1 | 15 | aaaa | 10 |
| 1 | 12 | bbbb | 15 |
| 1 | 38 | cccc | 29 |
In my PHP code I am using the following to define the text boxes:
foreach($_POST['number'] as $i => $item) {
When I execute the script I only get the data of the first three textboxes. I get in my database:
| session_id | number | name | price |
|-------------|----------|----------|----------|
| 1 | 15 | aaaa | 10 |
After weeks of doing research I have discovered that there is something wrong with the JavaScript part of the code. When I send the data with the text boxes in the second example I get the result I want. When I use JavaScript to create the dynamic text boxes the PHP script will only post the first row (that is not created with JavaScript) to the database.
What is wrong with my script?
Here is the script I am using to add data to my database:
<?php
$correct = true;
$_SESSION['session_id'];
$number = $_POST['number'] ;
$name = $_POST['name'] ;
$price = $_POST['price'] ;
if($correct){
foreach($_POST['number'] as $i => $item) {
$db = new PDO('mysql:host=localhost;dbname=db', 'user', 'pass');
$query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";
$stmt = $db->prepare($query);
$exec = $stmt->execute(array(
':session_id' => $_SESSION['session_id'],
':number' => $_POST["number"][$i],
':name' => $_POST["name"][$i],
':price' => $_POST["price"][$i]
));
}
}
else
{
header('Location: ../error.php');
}
?>
Result of var_dump on $_POST['number']:
array(1) { [0]=> string(2) "15" }
The main problem is that all your fields in the form have the same name, even though they are supposed to be arrays, you're not really allowing for multiple rows.
The easiest (not necessarily the optimal) way is to make some tweaks
Change your form element names to
variable[$i][number]
variable[$i][name]
variable[$i][price]
and make sure your form changes the value for $i on each row, so that your form becomes:
<form name="reaction" id="reaction" method="post" action="./send.php">
<input type="text" name="variable[0][number]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="variable[0][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="variable[0][price]" id="price1" value="10" placeholder="Price 1" /> <br />
<input type="text" name="variable[1][number]" id="number1" value="15" placeholder="Number 1" /> <br />
<input type="text" name="variable[1][name]" id="name1" value="aaaa" placeholder="Name 1" /> <br />
<input type="text" name="variable[1][price]" id="price1" value="10" placeholder="Price 1" /> <br />
and so on...
Then, alter your form processing to iterate over $variable:
foreach($variable as $var)
{
$number = $var['number'];
$name = $var['name'];
$price = $var['price'];
// do whatever it is you do with the variables and then loop to the next row
}
that's it!
Like I said, this is not necessarily the best way to accomplish your goal, but it is by far the easiest
You can keep your form fields with the array names, but in order to post your data to the database, you will need to iterate through the array.
So your receiving page should collected all the form data in a $_POST variable, and then you can parse the posted values as $_POST['number'] and iterate through the array using a for-each loop.
foreach ($_POST['price'] as $key => $value) {
// do something with array value
echo "{$key} => {$value} ";
print_r($_POST['price']);
}
Dont inject pure html but play with DOM.
<form name="reaction" id="reaction" method="post" action="./send.php">
<button type="submit" class="btn btn-primary" name="send">Save</button><br />
</form>
<script>
function newInput(type, value, count){
var newInput = document.createElement('input');
newInput.type = 'text';
newInput.name = type+'[]';
newInput.id = type+count;
newInput.value = value;
newInput.placeholder = type+' '+count; // <--you probably want to camelize this
return newInput;
}
function addRow(number, name, price, count, target){
target.appendChild(newInput('number', number, count));
target.appendChild(newInput('name', name, count));
target.appendChild(newInput('price', price, count));
target.appendChild(document.createElement('br')); // <-- create any element
}
var myForm = document.getElementById('reaction');
var count = 0;
addRow(111, 'one', 1, ++count, myForm);
addRow(222, 'two', 2, ++count, myForm);
addRow(333, 'three', 3, ++count, myForm);
addRow(444, 'four', 4, ++count, myForm);
</script>
PHP part looks almost OK:
$post_number = $_POST['number'];
$post_name = $_POST['name'];
$post_price = $_POST['price'];
//check, if needed set session variables here, then
$ses_id = session_id();
$db = new PDO('mysql:host=localhost;dbname=test', 'root', '');
$query= "INSERT INTO products(session_id, number, name, price) VALUES (:session_id, :number, :name, :price)";
foreach($_POST['number'] as $i => $item) {
$stmt = $db->prepare($query);
$exec = $stmt->execute(array(
':session_id' => $ses_id,
':number' => $post_number[$i],
':name' => $post_name[$i],
':price' => $post_price[$i]
));
if($exec == false)
header('Location: ../error.php');
//or print out what happened
//$e = $stmt->errorInfo();
//print_r($e);
//die();
}
I'm kind of new to Ajax, so I was wondering how I can store the values of radio buttons inside of an array, as I did for "question", "answer", and "testcases". I need to send the information through a PHP script, that's why I wanted to store the data. Any help would be appreciated, thanks.
<div id="container">
<form>
<div>
<input type='text' id='Question' class="form-control" placeholder="Question" />
<input type='text' id='Answer' class="form-control" placeholder="Answer" />
<input type='text' id='Testcases' class="form-control" placeholder="Testcases" />
<p style="margin-left:150px;">
<label>Difficulty level:</label>
<input type="radio" name="A" id='E' value="Easy" checked="checked" />
<label for='E'>Easy</label>
<input type="radio" name="A" id='M' value="Medium" />
<label for='M'>Medium</label>
<input type="radio" name="A" id='H' value="Hard" />
<label for='H'>Hard</label>
</p>
</div>
<input type='button' class='lg-button' onclick='send()' value='Submit' />
</form>
</div>
<script>
function send() {
var question = document.getElementById('Question').value;
var answers = document.getElementById('Answer').value;
var cases = document.getElementById('Testcases').value;
var ch = document.getElementsByName('A').value;
var data = {
'Question': question,
'Answer': answers,
'Testcases': cases,
'A': ch
};
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if (hr.readyState === 4) {
document.getElementById('send').innerHTML = hr.responseText;
}
};
hr.open("POST", "URL", true);
hr.send(JSON.stringify(data));
//alert(JSON.stringify(data));
}
</script>
Below is the working code,
function send() {
const question = document.getElementById('Question').value;
const answers = document.getElementById('Answer').value;
const testCases = document.getElementById('Testcases').value;
const level = document.querySelector('[name="A"]:checked').value;
const data = {
'Question': question || '',
'Answer': answers || '',
'Testcases': testCases || '',
'A': level
};
console.log(data);
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
document.getElementById('response').innerHTML = xhr.responseText;
}
};
xhr.open("POST", "URL", true);
xhr.send(JSON.stringify(data));
}
<div id="container">
<input type='text' id='Question' class="form-control" placeholder="Question" />
<input type='text' id='Answer' class="form-control" placeholder="Answer" />
<input type='text' id='Testcases' class="form-control" placeholder="Testcases" />
<p style="margin-left:150px;">
<label>Difficulty level:</label>
<input type="radio" name="A" id='E' value="Easy" checked="checked" />
<label for='E'>Easy</label>
<input type="radio" name="A" id='M' value="Medium" />
<label for='M'>Medium</label>
<input type="radio" name="A" id='H' value="Hard" />
<label for='H'>Hard</label>
</p>
<input type='button' class='lg-button' onclick='send()' value='Submit' />
<p id="response"></p>
</div>
I have a form in my app with several checkboxen. I want the result(value) of the checked checkedboxes saved into separate rows in the database, see below. The problem is that when saving, only the first one (Ma) is saved and the other ones not eventhough the are checked in the form. When MA is not checkend nothing happens at all... I use JqueryMobile/JavaScript/PhoneGap Build
Form:
<form name="test">
<label class="label_check" id="l1" for="ch1">Ma
<input class="custom" type="checkbox" name="checkgroup" id="ch1" value="Ma" />
</label>
<label class="label_check" id="l2" for="ch2">Di
<input class="custom" type="checkbox" name="checkgroup" id="ch2" value="Di" checked />
</label>
<label class="label_check" id="l3" for="ch3">Woe
<input class="custom" type="checkbox" name="checkgroup" id="ch3" value="Woe" />
</label>
<label class="label_check" id="l4" for="ch4">Do
<input class="custom" type="checkbox" name="checkgroup" id="ch4" value="Do" />
</label>
<label class="label_check" id="l5" for="ch5">Vr
<input class="custom" type="checkbox" name="checkgroup" id="ch5" value="Vr" checked />
</label>
<label class="label_check" id="l6" for="ch6">Za
<input class="custom" type="checkbox" name="checkgroup" id="ch6" value="Za" />
</label>
<label class="label_check" id="l7" for="ch7">Zo
<input class="custom" type="checkbox" name="checkgroup" id="ch7" value="Zo" />
</label>
</form>
</p>
<p>
<input type="button" name="saveData" id="btn1" value="Save" onclick="saveRecordSafety();"/>
Javascript:
function saveRecordSafety() {
//Write the record to the database
theDBbeter.transaction(insertRecordSafety, onTxErrorB, onTxSuccessB);
}
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.lenght; r++);
if (elementen[r].checked) {
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
I think the problem is because of your for loop being terminated by a semicolon:
for (var r= 0; r < elementen.lenght; r++);
Try this:
function insertRecordSafety(txb) {
var elementen = document.getElementsByName ("checkgroup");
var tmpChoise;
for (var r= 0; r < elementen.length; r++)
{
if (elementen[r].checked)
{
tmpChoise = elementen[r].value;
alert(tmpChoise);
var sqlStrB = 'INSERT INTO testSafetyBeter (beter) VALUES (?)';
txb.executeSql(sqlStrB, [tmpChoise], onSqlSuccess, onSqlError);
}
}
}
I've also spaced things out to make it easier to read.
I am trying to create a page total based on options selected from checkboxes.
here is my HTML markup:
<input type="checkbox" id="option1" name="option1" value="<?= $add[0] ?>" />t1 + £<?= $add[0] ?><br />
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" /t2 + £<?= $add[1] ?><br />
<input type="checkbox" id="option3" name="option3" value="<?= $add[2] ?>" />t3 + £<?= $add[2] ?><br />
<input type="checkbox" id="option4" name="option4" value="<?= $add[3] ?>" />t4 + £<?= $add[3] ?> <br />
This is my JavaScript that doesn't work:
var option1 = 0;
var option2 = 0;
var option3 = 0;
var option4 = 0;
var op = 0;
var extra = document.getElementById('extra');
$(":input").change(function()
{
option1 = $("input[name=option1]:checked").attr("value");
option2 = $("input[name=option2]:checked").attr("value");
option3 = $("input[name=option3]:checked").attr("value");
option4 = $("input[name=option4]:checked").attr("value");
op = parseInt(option1) + parseInt(option2) + parseInt(option3) + parseInt(option4) ;
extra.innerHTML = '<p>£'+op+'</p>';
});
Have I gone wrong somewhere?
I have other totals working, have removed from script so it's easier to read, just this one doesn't work!
EDITED:
<input id="option1" name="option1" value="20" type="checkbox">t1 + £20<br>
<input id="option2" name="option2" value="20" type="checkbox">t2 + £20<br>
<input id="option3" name="option3" value="20" type="checkbox">t3 + £20<br>
<input id="option4" name="option4" value="20" type="checkbox">t4 + £20 <br>
ADDED RADIO:
<input id="delivery" name="delivery" value="0" checked="checked" type="radio"> Standard (72hrs) - no addtional charges<br>
<input id="delivery" name="delivery" value="200" type="radio"> 45hrs - £200 per email templates<br>
<input id="delivery" name="delivery" value="250" type="radio"> 24hrs - £250 per email templates<br>
It would be easiest if you could select all your checkboxes together (and be sure you're not grabbing other checkboxes you don't want to grab:
<div id="checkSet">
<input type="checkbox" id="option1" name="option1" value="<?= $add[0] ?>" />t1 + £<?= $add[0] ?><br />
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" /t2 + £<?= $add[1] ?><br />
<input type="checkbox" id="option3" name="option3" value="<?= $add[2] ?>" />t3 + £<?= $add[2] ?><br />
<input type="checkbox" id="option4" name="option4" value="<?= $add[3] ?>" />t4 + £<?= $add[3] ?> <br />
</div>
then select all of them, and iterate over them, summing their values:
var sum = 0;
$('#checkSet :checked').each(function(){
sum += parseInt($(this).val(), '10');
});
There is an error in your html:
<input type="checkbox" id="option2" name="option2" value="<?= $add[1] ?>" />t2 + £<?= $add[1] ?><br />
Then when you do parseInt it's always better to specify the base you are parsing:
parseInt(option1, '10')
Otherwise you might have odd problems with values like 09.
Can I see the generated HTML output? Maybe one of the values of the checkboxes is not a number and can't be parsed.
Parsing it returns NaN and this gives you a problem when you add up the values.
I used this code and works but of course could be written much better
var extra = document.getElementById('extra');
$(":input").change(function()
{
var option1;
var option2;
var option3;
var option4;
var op = 0;
option1 = $("input[name=option1]:checked").attr("value");
option2 = $("input[name=option2]:checked").attr("value");
option3 = $("input[name=option3]:checked").attr("value");
option4 = $("input[name=option4]:checked").attr("value");
if (option1){
op += parseInt(option1, '10');
}
if (option2){
op += parseInt(option2, '10');
}
if (option3){
op += parseInt(option3, '10');
}
if (option4){
op += parseInt(option4, '10');
}
if (op > 0){
extra.innerHTML = '<p>£'+op+'</p>';
}else{
extra.innerHTML = '';
}
});
Look at the fiddle here