|
Finding out which radio button someone clicked in a form
I had this project to create a page that offered uniform sizes to a viewer based on a delimited list of sizes stored in a database. We needed to use AJAX methods to push the information back to the server because the web site application required a multi-step data entry process, with no page refreshes. Once I had queried the database for the record with the delimited list, I parsed the list with PHP and created the radio buttons with the following PHP:
// create an array of shirts from the delimited list... $shirts = split(":", $my_shirts);
// loop through the array and create the radio button list... for ($i=0; $i<count($shirts); $i++) { if ($shirts[$i] != "") { $shirtRadios .= "<input type=\"radio\" id=\"shirtRadio\" value=\"" . $shirts[$i] . "\"> " . $shirts[$i] . "<br />"; } }
The loop basically creates a big string with all the radio buttons needed. The value of the button is what we show as the button option too; like S, M, L, XL, etc. The key point is that we create all the buttons with the same ID so that we have a valid HTML radio button array. Later we echo out the string as part of the HTML form...
echo " <td valign=\"top\" width=\"100\"> Shirt: <br /><br />$shirtRadios<br /><br /> </td> ";
When the user submits the form, we process it through JavaScript in order to handle form validation (the subject of a different post). This part of the form validation loops through the DOM object called shirtRadio we built with the PHP code, and we set a variable called myShirtSize with the checked radio button value. Later we can send that value back to the server.
/* build string for shirt sizes*/ function findTheShirtSize (theForm) { var myShirtSize = ""; for (i = 0; i < theForm.shirtRadio.length; i++) { var checked = theForm.shirtRadio[i].checked; if (checked) { myShirtSize += theForm.shirtRadio[i].value + ":"; } } }
The important points are passing the ID of the form to the function, and then we can reference the radio array. We can use the .length value for the loop counter. The shirtRadio object is an array, so we can reference it with the [i] array position identifier, and the .checked property tells us if it was clicked by the user. Then we can use its .value property to find the options value.
I chose not to use the reference by name or id methods because discretely calling the actual object always works for me. If this method the most ideal? You decide, but maybe this is a good place to start.
|
|
|
|
|
Click here to advertise! |