1

Is it possible to conditionally add hidden input fields into a form?

eg I have a php form that is adding values to a table and if the appleID = 1 or 2 then I want 1 added to the fruits column of my table and if appleID =3 I want 1 added to the sweets column of my table. I thought I might be able to do something like the below but it is adding all hidden values no matter what I select. Or should I approach this a different way?

<input type="radio" value="1" name="appleID" />
<input type="hidden" value="1" name="fruits" />
<input type="hidden" value="0" name="sweets" />

<input type="radio" value="2" name="appleID" />
<input type="hidden" value="1" name="fruits" />
<input type="hidden" value="0" name="sweets" />

<input type="radio" value="3" name="appleID" />
<input type="hidden" value="0" name="fruits" />
<input type="hidden" value="1" name="sweets" />

Thanks I haven't done much with php so I will need to explore that option further. Thanks for the feedback. I was also looking at something like the below. But PHP sounds likes the better option. change field value when select radio buttons

Community
  • 1
  • 1
ak85
  • 4,154
  • 18
  • 68
  • 113

2 Answers2

1

You can either use all values in the radio buttons (1,1,0 - 2,1,0 - 3,0,1) and split them after receiving them in your PHP script or add/delete the hidden fields via JavaScript.

Split Example:

HTML:

<input type="radio" value="1,1,0" name="appleID" />
<input type="radio" value="2,1,0" name="appleID" />
<input type="radio" value="3,0,1" name="appleID" />

PHP:

if (!empty($_POST['appleID']))
{
    list($appleID, $fruits, $sweets) = explode(",", $_POST['appleID']);
}
Christoph Winkler
  • 6,278
  • 1
  • 18
  • 18
  • Thanks I haven't done much with php so I will need to explore that option further. Thanks for the feedback. I was also looking at something like the below. But PHP sounds likes the better option. http://stackoverflow.com/questions/1322525/change-field-value-when-select-radio-buttons – ak85 Apr 17 '12 at 21:25
0

It is better to put that logic into the PHP script instead of using Javascript - because you have to do the validation anyway.

Ed Heal
  • 59,252
  • 17
  • 87
  • 127