Curious13
Curious13

Reputation: 329

Radio button not checked breaks page but works if checked

I have a simple form that I'm trying to pass data to which on the action page has an email that sends the data that I put into the form.

On my form page. I have a text field and two radio buttons.

My text field works if I don't put data into it. However, on my radio buttons the page works if I check it but doesnt work if I don't check it at all which results in my page breaking I'm not sure what I'm doing wrong? I want the page to process the default to "no" if I didn't check either radio buttons. Do I have to validate or something?

Here is my code.

<cfparam name="form.firstName" default="">
<cfparam name = "form.optradio1" default="no">

<form action="test.cfm" method="post">
  <label for="firstName"></label>
  <input type="text" name="firstName">
  <input type="radio" name="optradio1" Value="Male" <cfif form.optradio1 eq "Yes">checked</cfif>>
</form>

Upvotes: 1

Views: 142

Answers (1)

Alex
Alex

Reputation: 7833

That's how radio and checkbox inputs work in HTML. If they are not checked, they are not submitted on the form submit.

To determine if the radio input was checked, you can use
structKeyExists(form, <name of the input, as string>) as in
structKeyExists(form, "optradio1").

<cfparam name="form.firstName" default="">

<form action="test.cfm" method="post">
  <label for="firstName"></label>
  <input type="text" name="firstName">
  <input type="radio" name="optradio1" Value="Male" <cfif structKeyExists(form, "optradio1")>checked</cfif>>
</form>

Assuming you have two radio inputs:

<cfparam name="form.firstName" default="">

<form action="test.cfm" method="post">
  <label for="firstName"></label>
  <input type="text" name="firstName">
  <input type="radio" name="optradio1" Value="Male" <cfif structKeyExists(form, "optradio1") and form.optradio1 eq "Male">checked</cfif>>
  <input type="radio" name="optradio1" Value="Female" <cfif structKeyExists(form, "optradio1") and form.optradio1 eq "Female">checked</cfif>>
</form>

Your initial code doesn't work because:

  • if checked, form.optradio1 was equal to Male
  • if not checked, form.optradio1 was defaulted to no because of
    <cfparam name = "form.optradio1" default="no">

Upvotes: 3

Related Questions