Avatar of DeniseBarker
DeniseBarker
 asked on

Need form textfield validation only required when radio button selection is "yes"

I have a radio button on a form and in the hidden table row below it, a hidden textfield.  When the "yes" option is selected on the radio button, javascript code makes the table row visible so the user can now see the textfield to fill it in.   Problem:  I want to make this textfield required using ColdFusion MX 7 onsubmit, onserver settings;  when submitting the form, if the radio button option is "no", and this textfield is hidden, I get an error stating to fill in the textfield (but I can't because it's hidden).   I really only need the textfield to be required when it is visible (user has chosen "yes" on the radio button).   I'm new to CF and even newer to Javascript --- how can I make this textfield required only when the radio button is selected "yes"??  Thanks so very much!!
Web Languages and StandardsJavaScriptColdFusion Language

Avatar of undefined
Last Comment
_agx_

8/22/2022 - Mon
Zvonko

Show your validation you have so far.
It is easier to extend a script then to create a new one from scratch.

DeniseBarker

ASKER
Sorry -- should have posted this before......
      
JAVASCRIPT............................................................

      function showLotusNotesProg(){
                  var isLotusNotes = document.getElementById("isLotusNotes");
                  var otherTB = document.getElementById("lotusNotesItems");
                  if (isLotusNotes.checked == true){
                        if(InternetExplorer){
                              otherTB.style.display="inline";
                        }else{
                              otherTB.style.display="table-row";
                        }
                  }else{
                        otherTB.style.display="none";
                  }
            }


FORM ========================
(Sorry --- this instance actually uses a select box, but I've two other similar items on this form that will need the same type of code and they use radio buttons and text fields..... )

    <tr>
      <td width="29%" class="lineheight_1andahalf"><p>Is this a Lotus Notes request?<span class="reqAsterisk">*</span> </p></td>
      <td width="71%"><p>
              <cfinput type="radio" name="isLotusNotes" id="isLotusNotes" value="1"
                  onClick="showLotusNotesProg();" >
                    Yes    &nbsp;&nbsp;&nbsp;&nbsp;
             <cfinput type="radio" name="isLotusNotes" checked="true" id="isLotusNotes" value="0"
                  onClick="showLotusNotesProg();">
                     No          </p></td>
      </tr>
   
    <tr id="lotusNotesItems" style="display:none">
        <td class="lineheight_1andahalf"><p>Lotus Notes Program Name:<span class="reqAsterisk">*</span></p></td>
      <td><p>
            <cfselect name="LotusNotesProg" class="selectbox" id="LotusNotesProg"
                  query="getLotusNotesPrograms"
                  value="lotusNotesProgID"
                  display="lotusNotesProgName"
                  selected="#lotusNotesProgName#">
            <option value="" selected></option>
            </cfselect>

      </p></td>
      </tr>

Thanks for the prompt response!!!!


Zvonko

I was also not clear.
Can you please show the Validation for the form that you have so far.
And please post also the HTML source from browser page, not the ColdFusion source.

Experts Exchange has (a) saved my job multiple times, (b) saved me hours, days, and even weeks of work, and often (c) makes me look like a superhero! This place is MAGIC!
Walt Forbes
_agx_

@DeniseBarker,

I don't know if this will work, but in older versions of CF you could make a field mandatory by including a hidden form field with the same name and the word "_required" after it.

<input name="myField">
<input name="myField_required">

So maybe you maybe you could use javascript to add the required field whenever the radio button "yes" is checked, and remove it when "no" is checked.

http://developer.mozilla.org/en/docs/DOM:document.createElement

DeniseBarker

ASKER
aqx ---  appreciate your comments.   As I'm a newbie at Javascript, how would the code be written to do what you suggested?  I've tried various Javascript examples for the last several days, but can't get any of them to work...

For Zvonko ---  here's my code from the browser window...   If you still need something else, please let me know....  Your help is much appreciated...

<script type="text/javascript" src="/CFIDE/scripts/cfform.js"></script>
<script type="text/javascript" src="/CFIDE/scripts/masks.js"></script>
<script type="text/javascript">
<!--
    function  _CF_checkTechRequest(_CF_this)
    {
        //reset on submit
        _CF_error_exists = false;
        _CF_error_messages = new Array();
        _CF_error_fields = new Object();
        _CF_FirstErrorField = null;

        //form element reqTitle required check
        if( !_CF_hasValue(_CF_this['reqTitle'], "TEXT", false ) )
        {
            _CF_onError(_CF_this, "reqTitle", _CF_this['reqTitle'].value, "Please enter a Title for this Technical Request.");
            _CF_error_exists = true;
        }

        //form element contactFirstName required check
        if( !_CF_hasValue(_CF_this['contactFirstName'], "TEXT", false ) )
        {
            _CF_onError(_CF_this, "contactFirstName", _CF_this['contactFirstName'].value, "Please enter your First Name.");
            _CF_error_exists = true;
        }

        //form element contactLastName required check
        if( !_CF_hasValue(_CF_this['contactLastName'], "TEXT", false ) )
        {
            _CF_onError(_CF_this, "contactLastName", _CF_this['contactLastName'].value, "Please enter your Last Name.");
            _CF_error_exists = true;
        }

        //form element contactPhone required check
        if( _CF_hasValue(_CF_this['contactPhone'], "TEXT", false ) )
        {
            //form element contactPhone 'TELEPHONE' validation checks
            if (!_CF_checkphone(_CF_this['contactPhone'].value, true))
            {
                _CF_onError(_CF_this, "contactPhone", _CF_this['contactPhone'].value, "Please enter your Phone Number.");
                _CF_error_exists = true;
            }

        }else {
            _CF_onError(_CF_this, "contactPhone", _CF_this['contactPhone'].value, "Please enter your Phone Number.");
            _CF_error_exists = true;
        }

        //form element contactEmail required check
        if( _CF_hasValue(_CF_this['contactEmail'], "TEXT", false ) )
        {
            //form element contactEmail 'EMAIL' validation checks
            if (!_CF_checkEmail(_CF_this['contactEmail'].value, true))
            {
                _CF_onError(_CF_this, "contactEmail", _CF_this['contactEmail'].value, "Please enter your Email Address.");
                _CF_error_exists = true;
            }

        }else {
            _CF_onError(_CF_this, "contactEmail", _CF_this['contactEmail'].value, "Please enter your Email Address.");
            _CF_error_exists = true;
        }

        //form element webURL required check
        if( !_CF_hasValue(_CF_this['webURL'], "TEXT", false ) )
        {
            _CF_onError(_CF_this, "webURL", _CF_this['webURL'].value, "Please enter the Web Address of the page needing attention.");
            _CF_error_exists = true;
        }

        //form element description required check
        if( !_CF_hasValue(_CF_this['description'], "TEXTAREA", false ) )
        {
            _CF_onError(_CF_this, "description", _CF_this['description'].value, "Please enter description of problem or request.");
            _CF_error_exists = true;
        }

        //form element errorMessage required check
        if( !_CF_hasValue(_CF_this['errorMessage'], "TEXTAREA", false ) )
        {
            _CF_onError(_CF_this, "errorMessage", _CF_this['errorMessage'].value, "Please cut and paste error Message.");
            _CF_error_exists = true;
        }


        //display error messages and return success
        if( _CF_error_exists )
        {
            if( _CF_error_messages.length > 0 )
            {
                // show alert() message
                _CF_onErrorAlert(_CF_error_messages);
                // set focus to first form error, if the field supports js focus().
                if( _CF_this[_CF_FirstErrorField].type == "text" )
                { _CF_this[_CF_FirstErrorField].focus(); }

            }
            return false;
        }else {
            return true;
        }
    }
//-->
</script>

<script language="javascript">
            var InternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
      
            function showLotusNotesProg(){
                  var isLotusNotes = document.getElementById("isLotusNotes");
                  var otherTB = document.getElementById("lotusNotesItems");
                  if (isLotusNotes.checked == true){
                        if(InternetExplorer){
                              otherTB.style.display="inline";
                        }else{
                              otherTB.style.display="table-row";
                        }
                  }else{
                        otherTB.style.display="none";
                  }
            }
            
            function showWebURL(){
                  var webPageExist = document.getElementById("webPageExist");
                  var otherTB = document.getElementById("webURLItems");
                  if (webPageExist.checked == true){
                        if(InternetExplorer){
                              otherTB.style.display="inline";
                        }else{
                              otherTB.style.display="table-row";
                        }
                  }else{
                        otherTB.style.display="none";
                  }
            }

            function showErrorMessage(){
                  var isBug = document.getElementById("isBug");
                  var otherTB = document.getElementById("errorMessageItems");
                  if (isBug.checked == true){
                        if(InternetExplorer){
                              otherTB.style.display="inline";
                        }else{
                              otherTB.style.display="table-row";
                        }
                  }else{
                        otherTB.style.display="none";
                  }
            }
</script>

<form name="TechRequest" id="TechRequest" action="TechRequest_CF.cfm" method="post" onsubmit="return _CF_checkTechRequest(this)">
  <input type="hidden" name="action" value="add">
  <br>
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td height="40" colspan="4" class="table_valigntop"><h1>Create New Tech Request... </h1></td>
      <td class="table_valigntop"><p><span class="reqAsterisk">*</span>Required Field</p></td>
    </tr>
    <tr>
      <td width="19%" class="lineheight_1andahalf"><p>Request Title:<span class="reqAsterisk">*</span></p></td>
      <td colspan="2"><p>
        <input name="reqTitle" type="text" maxlength="70"  size="42"  class="selectbox"  id="reqTitle"  />
      </p></td>
      <td width="17%"><p>&nbsp;</p></td>
      <td width="16%"><p>&nbsp;</p></td>
    </tr>
    <tr>
      <td class="lineheight_1andahalf"><p> Contact First Name:<span class="reqAsterisk">*</span></p></td>
      <td colspan="2"><p>
        <input name="contactFirstName" type="text" maxlength="70"  size="42"  class="selectbox"  id="contactFirstName"  />
      </p></td>
      <td><p>&nbsp;</p></td>
      <td><p>&nbsp;</p></td>
    </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Contact Last Name:<span class="reqAsterisk">*</span> </p></td>
      <td colspan="2"><p>
        <input name="contactLastName" type="text" maxlength="70"  size="42"  class="selectbox"  id="contactLastName"  />
        </p></td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Contact Phone:<span class="reqAsterisk">*</span> </p></td>
      <td colspan="2"><p>
        <input name="contactPhone" type="text" maxlength="15"  size="42"  class="selectbox"  id="contactPhone"  />
      </p></td>
      <td><p>&nbsp;</p></td>
      <td><p>&nbsp;</p></td>
    </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Contact Email:<span class="reqAsterisk">*</span> </p></td>
      <td colspan="2"><p>
        <input name="contactEmail" type="text" maxlength="140"  size="42"  class="selectbox"  id="contactEmail"  />
      </p></td>
      <td><p>&nbsp;</p></td>
      <td><p>&nbsp;</p></td>
    </tr>
  </table>
  <table width="100%" border="0" cellspacing="0" cellpadding="0">
   
    <tr>
      <td width="29%" class="lineheight_1andahalf"><p>Is this a Lotus Notes request?<span class="reqAsterisk">*</span> </p></td>
      <td width="71%"><p>
              <input name="isLotusNotes" type="radio" value="1" onclick="showLotusNotesProg();"  id="isLotusNotes"  />
                    Yes    &nbsp;&nbsp;&nbsp;&nbsp;
             <input name="isLotusNotes" type="radio" value="0" onclick="showLotusNotesProg();"  checked="checked"  id="isLotusNotes"  />
                     No          </p></td>
      </tr>
   
    <tr id="lotusNotesItems" style="display:none">
        <td class="lineheight_1andahalf"><p>Lotus Notes Program Name:<span class="reqAsterisk">*</span></p></td>
      <td><p>
            <select name="LotusNotesProg" class="selectbox"  id="LotusNotesProg" >
    <option value="1">Calendar of Events</option>
    <option value="2">ICS</option>
    <option value="3">Online Learning </option>
    <option value="4">TPC</option>
    <option value="5">Teacher Job Network</option>
    <option value="6">Videoconference</option>
    <option value="7">Staff Development</option>
    <option value="8">Preview Center</option>
    <option value="9">Crystal Reports</option>
    <option value="10">School Directory</option>
    <option value="11">User Registration</option>
    <option value="12">Region 10 Directory</option>
    <option value="13">Annual School Calendar</option>
    <option value="14">E-Reports</option>
    <option value="15">Service Issues</option>
    <option value="16">HR Workflow</option>
    <option value="17">Integra</option>
    <option value="18">Other</option>

            <option value="" selected></option>
            </select>

      </p></td>
      </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Does Web Page already exist?<span class="reqAsterisk">*</span> </p></td>
      <td><p>
        <input name="webPageExist" type="radio" value="1" onclick="showWebURL();"  id="webPageExist"  />
                          Yes    &nbsp;&nbsp;&nbsp;&nbsp;
        <input name="webPageExist" type="radio" value="0" onclick="showWebURL();"  checked="checked"  id="webPageExist"  />
                          No     </p></td>
      </tr>
    <tr id="webURLItems" style="display:none">
      <td class="lineheight_1andahalf"><p>Web URL:<span class="reqAsterisk">*</span> </p></td>
      <td><p>
        <input name="webURL" type="text" maxlength="250"  size="75"  class="selectbox"  id="webURL"  />
          </p></td>
      </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Request Description:<span class="reqAsterisk">*</span> </p></td>
      <td><p>
        <textarea name="description" cols="72" rows="4" wrap="virtual" class="selectbox" id="description" ></textarea>
      </p></td>
      </tr>
    <tr>
      <td class="lineheight_1andahalf"><p>Is there a program bug?<span class="reqAsterisk">*</span> </p></td>
      <td><p>
        <input name="isBug" type="radio" value="1" onclick="showErrorMessage();"  id="isBug"  />
                        Yes     &nbsp;&nbsp;&nbsp;&nbsp;
            <input name="isBug" type="radio" value="0" onclick="showErrorMessage();"  checked="checked"  id="isBug"  />
                        No      </p></td>
      </tr>
    <tr id="errorMessageItems" style="display:none">
      <td class="lineheight_1andahalf"><p>Error message:<span class="reqAsterisk">*</span> </p></td>
      <td><p>
        <textarea name="errorMessage" cols="72" rows="4" wrap="virtual" class="selectbox" id="errorMessage" ></textarea>
      </p></td>
      </tr>
    <tr>
      <td class="lineheight_1andahalf" height="65"><p>
        
        <input name="SubmitBtn" type="submit" value="Submit" id="SubmitBtn"  />
</p></td>
      <td><p>&nbsp;</p></td>
      </tr>
  </table>
  <p>&nbsp;</p>
   <input type='hidden' name='reqTitle_CFFORMREQUIRED' value='Please enter a Title for this Technical Request.'>
<input type='hidden' name='contactFirstName_CFFORMREQUIRED' value='Please enter your First Name.'>
<input type='hidden' name='contactLastName_CFFORMREQUIRED' value='Please enter your Last Name.'>
<input type='hidden' name='contactPhone_CFFORMTELEPHONE' value='Please enter your Phone Number.'>
<input type='hidden' name='contactPhone_CFFORMREQUIRED' value='Please enter your Phone Number.'>
<input type='hidden' name='contactEmail_CFFORMEMAIL' value='Please enter your Email Address.'>
<input type='hidden' name='contactEmail_CFFORMREQUIRED' value='Please enter your Email Address.'>
<input type='hidden' name='webURL_CFFORMREQUIRED' value='Please enter the Web Address of the page needing attention.'>
<input type='hidden' name='description_CFFORMREQUIRED' value='Please enter description of problem or request.'>
<input type='hidden' name='errorMessage_CFFORMREQUIRED' value='Please cut and paste error Message.'>
</form>

Zvonko

Check this:




        //form element LotusNotesProg required check
        if( _CF_this.isLotusNotes[0].checked && _CF_this.LotusNotesProg.value == "")
        {
            _CF_onError(_CF_this, "LotusNotesProg", "", "Please select LotusNotes topic.");
            _CF_error_exists = true;
        }
           
         
        //form element webURL required check
        if( _CF_this.webPageExist[0].checked && !_CF_hasValue(_CF_this['webURL'], "TEXT", false ) )
        {
            _CF_onError(_CF_this, "webURL", _CF_this['webURL'].value, "Please enter the Web Address of the page needing attention.");
            _CF_error_exists = true;
        }

        //form element description required check
        if( !_CF_hasValue(_CF_this['description'], "TEXTAREA", false ) )
        {
            _CF_onError(_CF_this, "description", _CF_this['description'].value, "Please enter description of problem or request.");
            _CF_error_exists = true;
        }

               
        //form element errorMessage required check
        if( _CF_this.isBug[0].checked && !_CF_hasValue(_CF_this['errorMessage'], "TEXTAREA", false ) )
        {
            _CF_onError(_CF_this, "errorMessage", _CF_this['errorMessage'].value, "Please cut and paste error Message.");
            _CF_error_exists = true;
        }


        //display error messages and return success
        if( _CF_error_exists )
        {
            if( _CF_error_messages.length > 0 )
            {
                // show alert() message
                _CF_onErrorAlert(_CF_error_messages);
                // set focus to first form error, if the field supports js focus().
                if( _CF_this[_CF_FirstErrorField].type == "text" )
                { _CF_this[_CF_FirstErrorField].focus(); }

            }
            return false;
        }else {
            return true;
        }
    }
//-->
</script>



âš¡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.
_agx_

@DeniseBarker,

I tried the "_required" field idea and it works. But not in the way you want.

Using a "_required" field invokes server-side validation. Meaning the form is submitted (first) and afterward CF displays an error page with the names of the missing/invalid field entries.  I think you're looking for client-side validation. Meaning, use javascript to display warning messages before the form is submitted.   (Though its not a bad idea to use both, but that's another topic..)

Normally I would suggest adding a function to the cfform onSubmit method, but there is a cfform onSubmit bug (bug number 59602). Two possibilities are mentioned in the bottom comments here
http://livedocs.adobe.com/coldfusion/7/htmldocs/00000256.htm

1) Use a custom javascript function and the onValidate attribute of your cfinput textbox
2) Use a generic javascript function and the onValidate attribute of a hidden cfinput field
3) A third option is to use a hack. Set the textbox to required="yes" and input a fake value whenever the "NO" radio button is checked.

Here is an example using option #1

<!---
Form field element ids should be unique. The radio button ids were changed to:

isLotusNotesYes  
isLotusNotesNo
--->

<script type="text/javascript">
//*** Setting default variable for this example only ***
var InternetExplorer = true;

function showLotusNotesProg(){
      var isLotusNotes = document.getElementById("isLotusNotesYes");
    var otherTB = document.getElementById("lotusNotesItems");
      var linkedFieldID = 'LotusNotesProg';
    if (isLotusNotes.checked) {
            otherTB.style.display = (InternetExplorer ? "inline" : "table-row");
     }
       else{
           otherTB.style.display="none";
     }
  }
 
  function validateLotusNotesProg(frmObject, txtBoxObject, txtBoxValue) {
        var isLotusNotes = document.getElementById("isLotusNotesYes");
        //if the YES radio button was found AND is checked
        if (isLotusNotes && isLotusNotes.checked) {
              //First: remove all whitespace from the textBoxvalue
              //if value contains non-whitespace characters:  isNonEmpty will == true
              //if value was only whitespace: isNonEmpty will == false
              //false (means validation failed), true (means successful validation)
              var textBoxValue = txtBoxValue.replace(/\s+/g,'');
              var isNonEmpty  = (textBoxValue.length > 0);
              return isNonEmpty;
        }
        //Otherwise, the NO radio button was checked.      So an entry
        //is not required.  Return true to indicate validation success
        return true;
  }
</script>

<cfform id="myForm" method="post" action="myPage.cfm">
      <table>
      <tr>
      <td width="29%" class="lineheight_1andahalf"><p>Is this a Lotus Notes request?<span class="reqAsterisk">*</span> </p></td>
      <td width="71%"><p>
              <cfinput type="radio" name="isLotusNotes" id="isLotusNotesYes" value="1" onClick="showLotusNotesProg();" >
                    Yes    &nbsp;&nbsp;&nbsp;&nbsp;
             <cfinput type="radio" name="isLotusNotes" id="isLotusNotesNo" value="0" checked="true" onClick="showLotusNotesProg();">
                     No          </p></td>
      </tr>  
        <tr id="lotusNotesItems" style="display:none">
        <td class="lineheight_1andahalf"><p>Lotus Notes Program Name:<span class="reqAsterisk">*</span></p></td>
            <td><p><cfinput name="LotusNotesProg" id="LotusNotesProg" OnValidate="validateLotusNotesProg" message="LotusNotesProg is required"></p></td>
      </tr>  
      </table>
      <input type="submit">       
</cfform>
_agx_

@Zvonko,

Your suggestion is a good one for regular html forms. I don't know if you're using ColdFusion, but CFFORMs work a little differently. The javascript code posted by DeniseBarker is generated automatically by ColdFusion. It doesn't really exist until the page is viewed/compiled. So unfortunately its not as simple as modifying an existing javascript function. That said, there may be simpler solutions than what I've suggested.
Zvonko

If you want help from me then open your own question ;-)
All of life is about relationships, and EE has made a viirtual community a real community. It lifts everyone's boat
William Peck
_agx_

Umm.... I just meant your suggestion won't work for the asker because they're using a cfform ;-)
_agx_

But it IS a solid suggestion if they were using a regular html form :)
ASKER CERTIFIED SOLUTION
_agx_

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.