note 50411 added to faq.html

From: Date: Sun, 27 Feb 2005 17:09:54 +0000
Subject: note 50411 added to faq.html
Groups: php.notes 
Request: Send a blank email to php-notes+get-85641@lists.php.net to get a copy of this message
Further to my note posted on 26-Feb-2005 at 04:44, I have refined the JavaScript function "send_picks()" to make it more robust and universal. The original version was designed to handle string keys and +ve integer key values only; fine for the original purpose of handling random picks for a shopping cart application but it produced a mal-formed array if any -ve or non-integer key values were submitted. The new version treats both keys and key values as strings, irrespective of the data type; and we all know just how easy it is to manipulate numeric strings as numbers in PHP:-). Key values can now be anything you like; including: "5" "2 dozen" "A gross" "12.5" "blue" and so forth. Here's the updated code: <script type="text/javascript"> function send_picks() { form1.picks.value=""; var e, picked = 0; for (var i = 0 ; i < form1.elements.length - 2; i++) { e = form1.elements[i]; if(e.value != "0" && e.value.length > 0) { e = form1.elements[i] picked++; form1.picks.value = form1.picks.value + "s:" + e.name.length + ":\"" + e.name + "\";s:" + e.value.length + ":\"" + e.value + "\";"; } } form1.picks.value = "a:" + picked + ":{" + form1.picks.value + "}"; } </script> Note the line: for (var i = 0 ; i < form1.elements.length - 2; i++) The "-2" term is to let the function skip the last 2 elements in the form, a "hidden" input and the "submit" button. No doubt different form layouts will need a different value here. An incidental bonus is that getting JavaScript to process a floating point input as a string rather than a number avoids the usual rounding errors that tend to turn an input such as "1.2" into a number beginning 1.199999... with about 30 places of decimals - yes, its JavaScript rather than PHP that is responsible for this kind of behaviour. ---- Manual Page -- http://www.php.net/manual/en/faq.html.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+50411 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+50411&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+50411&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+50411&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+50411&report=yes&reason=useless Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+50411&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+50411&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#85641) next »