Tech or Treat! Write an article about your scariest tech disaster to win gadgets!Learn more

x
?
Solved

Validating required radios based on text field

Posted on 2016-08-30
8
Medium Priority
?
87 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 1000 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
Plesk WordPress Toolkit

Plesk's WordPress Toolkit allows server administrators, resellers and customers to manage their WordPress instances, enabling a variety of development workflows for WordPress admins of all skill levels, from beginners to pros.

See why 2/3 of Plesk servers use it.

 
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 59

Accepted Solution

by:
Julian Hansen earned 1000 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 59

Expert Comment

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

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

Does your audience prefer people in photos or no people? How can you best highlight what you’re selling? What are your competitors doing, and what can you do that is different and unique from them?  Continue reading to learn how to make your images …
This article was originally published on Monitis Blog, you can check it here . Today it’s fairly well known that high-performing websites and applications bring in more visitors, higher SEO, and ultimately more sales. By the same token, downtime…
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
Learn how to create flexible layouts using relative units in CSS.  New relative units added in CSS3 include vw(viewports width), vh(viewports height), vmin(minimum of viewports height and width), and vmax (maximum of viewports height and width).
Suggested Courses

649 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