Solved

Validating required radios based on text field

Posted on 2016-08-30
8
56 Views
Last Modified: 2016-08-31
I have two address fields (HomeAddress1, BusinessAddress1). I also have a field where the user is supposed to select which address they want as their preferred mailing address.

I have a radio "group" where they can select which is their preference. It is defined as MailPrefBusi for the BusinessAddress1 field and  MailPrefHome for the HomeAddress1 field.

The preference is required and it must be one or the other as long as it is not empty. I initially set the one checked based on this code:
if ($("#BusinessAddress1").val() == "") {
    $("#MailPrefBusi").prop('checked', false);
    $("#MailPrefBusi").prop('disabled', true);
} else {
    $("#MailPrefBusi").prop('disabled', false);
}
if ($("#HomeAddress1").val() == "") {
    $("#MailPrefHome").prop('checked', false);
    $("#MailPrefHome").prop('disabled', true);
} else {
    $("#MailPrefHome").prop('disabled', false);
}

Open in new window

I have a function to validate that they selected a radio that corresponds to a field that is NOT empty. But this logic doesn't seem to work correctly. I'd like to get some new eyes on this to help fix the validation. Here is the validation function:
function checkMailingPrefs() {
    var prefs = ["MailPrefHome", "MailPrefBusi"];
    var field = ["HomeAddress1", "BusinessAddress1"];
    for (i = 0; i < 2; i++) {
        if ($("#" + prefs[i]).is(":checked") && $("#" + field[i]).val() == "") {
            $("#" + prefs[i]).prop('checked', false);
            $("#Error").html('You must select the correct Mailing Preference');
            return false;
        }
        if ($("#" + field[i]).val() !== "" || !$("#" + prefs[i]).is(":checked")) {
            $("#Error").html('You must select the correct Mailing Preference');
            return false;
        }
    }
    return true;
}

Open in new window

Even though I'm using JQuery ValidationEngine to validate the rest of the form, I cannot use it in this instance because it won't validate radios based on the value of a text field unless I use the funcCall validation.

Fiddle: https://jsfiddle.net/Mrbaseball34/y0Lkzgu7/

If anyone has a better way to do this, that would be even better...
0
Comment
Question by:EddieShipman
  • 3
  • 3
  • 2
8 Comments
 
LVL 8

Assisted Solution

by:James Bilous
James Bilous earned 250 total points
ID: 41777167
Shouldn't this:
        if ($("#" + field[i]).val() !== "" && !$("#" + prefs[i]).is(":checked")) {
            alert('You must select the correct Mailing Preference - 2');
            return false;
        }

Open in new window


Be this?:
        if ($("#" + prefs[i]).is(":checked") && $("#" + field[i]).val() == "") {
            alert('You must select the correct Mailing Preference - 2');
            return false;
        }

Open in new window


That being said, you might just want to use a validation engine function on the text field and in it error only if its corresponding radio isnt checked and its empty:

validate[optional,funcCall[checkType]]

Open in new window

and

function checkType(field, rules, i, option)
{
   //Check if field is blank
   //Check if radio is checked
}

Open in new window

0
 
LVL 26

Author Comment

by:EddieShipman
ID: 41777199
Did you modify the fiddle to see if your solution worked? I can't validate them individually because of the way they interact.
0
 
LVL 8

Expert Comment

by:James Bilous
ID: 41777268
If you look at what your second if statement is doing, its throwing an error if the business field isn't empty and the business radio is not checked. What you want to do is almost the exact same thing as you did earlier in your code, and throw an error if the business address field is empty and the business radio is checked.
0
 
LVL 26

Author Comment

by:EddieShipman
ID: 41777291
These are the four conditions:

1. if BusinessAddress is filled and HomeAddress empty, BusinessPref must be checked and HomePref should not be checked.
2. if HomeAddress is filled and BusinessAddress  is empty, HomePref must be checked and BusinessPref should not be checked.
3. if HomeAddress and BusinessAddress both filled, EITHER BusinessPref or HomePref must be checked.
4. if neither are filled neither can be checked, they would be disabled until one is filled then the corresponding Pref radio would be enabled, see enable_disableMailingPrefs() in Fiddle.
0
3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

 
LVL 8

Expert Comment

by:James Bilous
ID: 41777293
The change I recommend fulfills those 4 requirements.
0
 
LVL 52

Accepted Solution

by:
Julian Hansen earned 250 total points
ID: 41777797
I would change the markup and make use of custom attributes
HTML
<div id="Error" style="display: none"></div>
<form>
<div class="address-group">
  <label for="BusinessAddressSelect">Business Address</label>
  <textarea name="BusinessAddress1" id="BusinessAddress1" data-linked="BusinessAddressSelect" ></textarea>
  <input type="radio" value="BusinessAddress" name="preferred" id="BusinessAddressSelect" disabled /> Preferred

  <label for="HomeAddressSelect">Home Address</label>
  <textarea name="HomeAddress1" id="HomeAddress1" data-linked="HomeAddressSelect"></textarea>
  <input type="radio" value="HomeAddress" name="preferred" id="HomeAddressSelect" disabled /> Preferred

  <input type="submit"/>
</form>

Open in new window

jQuery
<script>
$(function() {
  $('form').submit(function() {
    return checkMailingPrefs();
  });
  
  $('.address-group textarea').keyup(function() {
    $("#Error").html('').hide();
    var linked = $('#' + $(this).data('linked'));

    var empty = $(this).val() == '';
    if (empty ) {
      linked.prop({disabled: true, checked: false});
    }
    else {
      linked.prop({disabled: false});
    }
  });
});

function checkMailingPrefs()
{
  if ($('.address-group input:checked').length > 0) 
    return true;
    
  $("#Error").html('You must select the correct Mailing Preference').show();
  
  return false;
}
</script>

Open in new window

Working sample here
0
 
LVL 26

Author Closing Comment

by:EddieShipman
ID: 41777884
Perfect Julian, Thx
0
 
LVL 52

Expert Comment

by:Julian Hansen
ID: 41777901
You are welcome.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This article discusses how to create an extensible mechanism for linked drop downs.
An enjoyable and seamless user experience can go a long way on an eCommerce site. While a cohesive layout and engaging copy play roles in creating a positive user experience, some sites neglect aspects that seem marginal but in actuality prove very …
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn how to look for a specific file type in a local or remote server directory using PHP.

910 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now