Form element name change with JavaScript and radio button

Today I have had to modify very complex script to change look of html form. It is quite easy to make changes in the form. But sometimes it is a problem to modify not to well written PHP script to receive data from new form.

In my case script was checking if the form was submitted with a button with given "name". In a new form I needed to move this value to html radio buttons.
Radio buttons need to have same name for all group - so I could not use it directly. I have decided to write a script that will change name of hidden field that would be submitted instead of button. In theory you may change name of every element of the form.

Main javascript looks like this (should be put in your code before the form - best place is HEAD section of your page):

<script type="text/javascript" language="JavaScript">
function NameChanger()
if(document.payment.rsubmit_post.checked == true) { = 'submit_post';
if(document.payment.rsubmit_transfer.checked == true) { = 'submit_transfer';
if(document.payment.rsubmit_cash.checked == true) { = 'submit_cash';
return true;
// -->

Every radio button with a new value needs one if statement in above script. To recognize which radio button have been clicked you need to give ID to each of them (or try to guess what position in form array may it have, but it would only work if form is not dynamic). In above script ID's of radio buttons are: "rsubmit_post", "rsubmit_transfer" and "rsubmit_cash". My hidden field ID was "methodinput". So if you want to add more radio buttons you may do it by adding if statements like this (don't forget to add html radio button field in the form as well :) ):

if(document.payment.RADIO_BUTTON_ID.checked == true) { = 'NEW_NAME';

Then your HTML form should be similar to this:

<form action="post.php" method="post" name="payment">
  <input type=hidden id="methodinput" name="default_name" >
  <input id="rsubmit_post" type="radio" name="method" onClick="return NameChanger();">Option One - Post Payment<br />
  <input id="rsubmit_transfer" type="radio" name="method" onClick="return NameChanger();">Option Two - Wire Transfer<br />
  <input id="rsubmit_cash" type="radio" name="method" onClick="return NameChanger();">Option Three - Cash<br />
  <input type="submit" value="Send me money!">

Your form should have set "name" value for itself as above! All radio buttons and a hidden fields must have given id.

Additionally with a little modification you may change "value" of every form element as well! Just change ".name" to ".value" in every if statement.

Believe me it is sometimes easier to add some javascript in a view layer than modify very complex PHP script! Let me know in the comments to this article if this solution have helped you. I hope it did :) .

5 Responses to “Form element name change with JavaScript and radio button”

Leave a Reply