0

I need to validate my form fields displayed in facebox.

The problem is that i am unable to get the values of the fields by using javascript.

for ex: document.form.field_name.value doesnt return its value.

Code sample :

<script type="text/javascript">
function validate()
{
  if (document.form1.field.value=='')
{
   alert ("Field cannot be left blank");
}
}

</script>


<form name="form1" onsubmit="return validate()">
<input type="text" name="field" /> 

</form>
Ashish Saxena
  • 434
  • 2
  • 8
  • 20

2 Answers2

0

A way to do this would be to pass the value directly from the form to the validation code.

<form name="form" id="form" onsubmit="return validate(this.field.value)">
<input type="text" id="field" /> 
</form>

Or you could even use a text box without the form using:

<input type="text" id="field" 
onkeydown="if (event.keyCode == 13) return validate(this.value)" />

Update the script to allow for the new value parameter:

<script type="text/javascript">
 function validate(val) {
   if (val.length < 1)
   {
      alert ("field cannot be left blank");
      return false; //to stop the default action of submitting the form
   } else {
      alert ("Value: "+val);
      return true; //allow to submit the page
   }
 }

</script>

This is actually a pretty easy and simple validation, but don't forget to set the return action based on whether you want the system to proceed with the submit or not.

I'm not sure where your pulling your page from whether from a remote html address or a locally stored div. So I'm not sure why your solution of pulling the value from the DOM does not work. I generally have no problems using jquery to get and set the values from the different fields in facebox windows.

NOTE: you have to be careful where you place your scripts. It depends on your application but sometimes you may want to place the script in the root document instead of the facebox page because if you load a remote facebox div you have a scope change and may need to refer to parent.document to access parent fields when the script is embedded in the remote facebox div.

RightHandedMonkey
  • 1,718
  • 20
  • 25
0

Facebox copies the chunk of DOM displayed, effectively creating elements with duplicate ids. This is not allowed by HTML standard. Your javascript goes bonkers looking for a single element uniquely identified by its id, yet it finds 2 of them...

This is a huge bug in Facebox. Any code in a facebox should not have ids. All your bindings should be renewed when the facebox is revealed.

Peter Lada
  • 383
  • 3
  • 12