how to set form field value on page load?

Jamoora 22 Apr, 2012
Here is my basically what I am trying to do...I have a hidden field called "posting_area" in my chronoform. On page load, I want to set the value of this field based on some simple logic. I could not find a way to set the form field value in php, so I tried to do it using javascript. I added a LoadJS code in the OnLoad event. But document.getElementById("posting_area") is always returning null irrespective of whether I put the LoadJS before of after ShowHtml. It seems to me that the LoadJS code is getting called even before the page is rendered and that's why it's not finding the form fields. I even tried putting the following jquery code. But even this does not find the field.
 $(document).ready(function() {
   if(document.getElementById("posting_area") != null)
   {
     alert("field found");
   }
   else
   {
     alert("field not found");
   }
 });

How do I set the value of the hidden field on page load? And is using javascript the right approach or should I use php? If php, how do I set the value of a field on a chronoform?
GreyHead 22 Apr, 2012
Hi Jamoora,

You don't say what the logic is that you want to apply so it's a bit hard to reply. I'd probably do it using PHP in a Custom Code action and put the value into the $form->data array; ChronoForms will apply these values to form inputs if the names match and if Try to Republish is set On in the Show HTML action (it is on by default).
<?php
// some code 
$form->data['posting_area'] = $some_value;
?>

You can also set a value with JavaScript - but you have the same problem of getting the value into the browser page. To delay the script until the Form HTML is loaded use the MooTools 'domready' event:
window.addEvent('domready', function() {
  if( $('posting_area') != null)
   {
     alert("field found");
   }
   else
   {
     alert("field not found");
   }
  );
});

Bob
Jamoora 22 Apr, 2012
Thanks Bob. I tried both ways and both of them worked just fine!
This topic is locked and no more replies can be posted.