Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

form validation 1

Status
Not open for further replies.

damipera

Technical User
Dec 1, 2005
134
GB
Hi guys! can u help me plz. I have a form and I want to make the textfield named 'firstname' to become mandatory if the user checks the radio with the 'No' label. How can I achieve this? Thanks.


Code:
<form id="formname" name="formname" method="post" action="">
  <label>
  Yes
  <input name="agree" type="radio" value="1" /> 
&nbsp;&nbsp;No </label>
  <label>
  <input name="agree" type="radio" value="0" />
  </label>
  <p>
    <input name="firstname" type="text" id="firstname" />
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="Submit" />
    </label>
  </p>
</form>
 
Put an "onsubmit" handler on your form, which checks to see which radio button is checked. If the radio button with the index of 1 (i.e. the second one) is checked, then return false if the firstname field is empty, true otherwise.

You can also print error messages, etc, as appropriate.

Hope this helps,
Dan

Coedit Limited - Delivering standards compliant, accessible web solutions

[tt]Dan's Page [blue]@[/blue] Code Couch
[/tt]
 
This should fix it [small](changes highlighted in red)[/small]
Code:
[!]<script type="text/javascript">

function validateForm(frm) {
   if (frm.elements["agree"][1].checked && !frm.elements["firstname"].value.length) {
      alert("You must supply a first name if you select 'No'");
      return false;
   }
   return true;
}

</script>[/!]

<form id="formname" name="formname" method="post" action="" [!]onsubmit="return validateForm(this)"[/!]>
  <label>
  Yes
  <input name="agree" type="radio" value="1" />
&nbsp;&nbsp;No </label>
  <label>
  <input name="agree" type="radio" value="0" />
  </label>
  <p>
    <input name="firstname" type="text" id="firstname" />
  </p>
  <p>
    <label>
    <input type="submit" name="Submit" value="Submit" />
    </label>
  </p>
</form>

-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
Your AWESOME kaht. Thank you very much!!!

Thanks also BillyRayPreachersSon.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top