Solved

Validating required radios based on text field

Posted on 2016-08-30
8
80 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 9

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 9

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
Don't Cry: How Liquid Web is Ensuring Security

WannaCry is just the start. Read how Liquid Web is protecting itself and its customers against new threats.

 
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
 
LVL 9

Expert Comment

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

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 57

Expert Comment

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

Featured Post

SharePoint Admin?

Enable Your Employees To Focus On The Core With Intuitive Onscreen Guidance That is With You At The Moment of Need.

Question has a verified solution.

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

Australian government abolished Visa 457 earlier this April and this article describes how this decision might affect Australian IT scene and IT experts.
When the s#!t hits the fan, you don’t have time to look up who’s on call, draft emails, call collaborators, or send text messages. An instant chat window is definitely the way to go, especially one like HipChat. HipChat is a true business app. An…
This tutorial demonstrates how to identify and create boundary or building outlines in Google Maps. In this example, I outline the boundaries of an enclosed skatepark within a community park.  Login to your Google Account, then  Google for "Google M…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

695 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