Solved

Validating required radios based on text field

Posted on 2016-08-30
8
50 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 7

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 7

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
What Should I Do With This Threat Intelligence?

Are you wondering if you actually need threat intelligence? The answer is yes. We explain the basics for creating useful threat intelligence.

 
LVL 7

Expert Comment

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

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 51

Expert Comment

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

Featured Post

IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Introduction JSON is an acronym for JavaScript Object Notation.  It is a text-string data transport mechanism, capable of representing simple or complex data structures in a consistent and easy-to-read manner.  Similar in concept to XML, but more e…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
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)

762 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

20 Experts available now in Live!

Get 1:1 Help Now