1

How do I validate that the input text corresponding to the radio option is checked?

screen capture

For example, using the image above:

  • If Contact 1's E-Mail radio option is selected, Contact 1's E-Mail text field cannot be blank, but Contact 1's Phone and US Mail text fields are still permitted.
  • If Contact 2's US Mail radio option is selected, Contact 2's US Mail text field cannot be blank, but Contact 2's Phone and E-Mail text fields are still permitted.

I have built the form above using the HTML below, but you can play with my Fiddle here: fiddle.

BEGIN UPDATE: I have a newer fiddle with better code here:

fiddle2

It has more instructions in the HTML and a closer attempt at my jQuery. For some reason, though, it still does not seem to be doing anything.

END UPDATE

I have tried naming the fields so that my jQuery can parse them, but that does not mean there is not a better way.

<body>
  <form name="jp2code" action="#" method="POST">
    <fieldset>
        <legend>Contact 1</legend>
        <span>
            <input type="radio" id="group1_PhoneRadio" name="group1"/>
            <label for="group1_PhoneText">Phone:</label>
            <input type="text" id="group1_PhoneText" name="group1_PhoneText"/>
            <br/>
            <input type="radio" id="group1_EMailRadio" name="group1"/>
            <label for="group1_EMailText">E-Mail:</label>
            <input type="text" id="group1_EMailText" name="group1_EMailText"/>
            <br/>
            <input type="radio" id="group1_USMailRadio" name="group1"/>
            <label for="group1_USMailText">US Mail:</label>
            <input type="text" id="group1_USMailText" name="group1_USMailText"/>
        </span>
    </fieldset>
    <fieldset>
        <legend>Contact 2</legend>
        <span>
            <input type="radio" id="group2_PhoneRadio" name="group2"/>
            <label for="group2_PhoneText">Phone:</label>
            <input type="text" id="group2_PhoneText" name="group2_PhoneText"/>
            <br/>
            <input type="radio" id="group2_EMailRadio" name="group2"/>
            <label for="group2_EMailText">E-Mail:</label>
            <input type="text" id="group2_EMailText" name="group2_EMaiText"/>
            <br/>                
            <input type="radio" id="group2_USMailRadio" name="group2"/>
            <label for="group2_USMailText">US Mail:</label>
            <input type="text" id="group2_USMailText" name="group2_USMailText"/>
        </span>
    </fieldset>
    <div>
      <input type="submit" name="submit" value="submit" />
    </div>
  </form>
</body>

What is the best way to write the jQuery?

I am new to jQuery, but I attempted my hand at it based on some Show/hide examples.

What I created below does not work, but hopefully indicates what I am trying to accomplish.

$(function() {
    $("input[type='radio']").change(function() { // when a radio button in the group changes
        var id = $(this).id;
        var index = id.indexOf('group');
        if (index == 0) { // is there a better way to do this?
          var groupN_Len = 7; // Length of 'groupN_'
          var radio_Len = 5; // Length of 'radio'
          var preStr = id.substring(0, groupN_Len);
          $"input[name*='preStr']".validate = null; // clear validation for all text inputs in the group
          var postStr = id.substring(groupN_Len + 1, id.Length() + 1 - radio_Len); // extract Phone, EMail, or USMail
          $(preStr+postStr+'Text').validate({ rules: { name: { required: true } } });
        }
    });
});
Community
  • 1
  • 1
  • You can use jQuery Validate. – Miguel Q. Jan 14 '14 at 22:27
  • There is some `validate` in my jQuery, but I don't know how to use it. –  Jan 14 '14 at 22:35
  • 1
    Please check this fiddle to see if this was what you are looking for. http://jsfiddle.net/zYkLF/1/ – tilda Jan 14 '14 at 23:30
  • +1 tilda. After the `.each(function()`, I need to somehow set all **validate rule** for all inputs in the same group to `required: false` before setting the **validate rule** for `$("input[name^="+checkboxId+"]")` to `required: true`. But, I don't know how to do that. –  Jan 15 '14 at 14:27
  • I'm not sure that I understand what you want. Please explain it with an example. – tilda Jan 15 '14 at 19:08
  • Newer code http://jsfiddle.net/jp2code/zYkLF/3/ –  Jan 15 '14 at 21:11
  • Check out dependency expressions in jQuery Validate. You can write `required:'#group2_USMailRadio:checked'` as a rule. – Ryley Jan 15 '14 at 23:21

2 Answers2

1

To make sure that the radiobutton is checked for each field, add attribute required="" in one of the radiobuttons for each fieldset.

demo

tilda
  • 676
  • 5
  • 8
0

OK, whatever radio button is selected in the Contact Group's Contact Preferences, that corresponding text field is required.

Here is where I am so far on my jQuery checking:

EDIT:

  1. Modified with tilda's important detail about adding '.' to the class name.
  2. Added Required Attribute: how to dynamically add REQUIRED attribute to textarea tag using jquery?
  3. Removed Required Attribute: jquery removing html5 required attribute

Final code works and looks like this:

<script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.js"></script>
<script type="text/javascript">
$(function() {
  jQuery.validator.setDefaults({
    debug: true,
    success: "valid"
  });
  $("input[type='radio']").change(function() {
    $('.'+$(this).attr('name')).each(function(index) {
      $(this).removeAttr('required');
    });
    if($(this).is(':checked')) {
      $('.'+$(this).attr('id')).each(function(index) {
        $(this).prop('required',true);
      });
    }
  });
  $('#submit').click(function() {
    $(this).validate();
  });
});

Back to the HTML of the document: I did a lot of subtle editing to the text by creating specific ids and names for the radio buttons that matched up with the class names for the text controls.

Here is that end result:

<body>
  <form name="jp2code" action="#" method="POST">
    <div>For each field below, provide the Phone Number, E-Mail Address, and Street Address. <b>Indicate the preferred contact method using the radio button.</b></div>
    <fieldset>
        <legend>Contact 1</legend>
        <span>
            <input type="radio" id="group1_Phone" name="group1"/>
            <label for="group1_Phone">Phone:</label>
            <input type="text" name="group1_PhoneText" class="group1 group1_Phone" />
            <br/>
            <input type="radio" id="group1_EMail" name="group1"/>
            <label for="group1_EMail">E-Mail:</label>
            <input type="text" name="group1_EMailText" class="group1 group1_EMail" />
            <br/>
            <input type="radio" id="group1_USMail" name="group1"/>
            <label for="group1_USMail">US Mail:</label>
            <input type="text" name="group1_USMailText" class="group1 group1_USMail" />
        </span>
    </fieldset>
    <fieldset>
        <legend>Contact 2</legend>
        <span>
            <input type="radio" id="group2_Phone" name="group2"/>
            <label for="group2_Phone">Phone:</label>
            <input type="text" name="group2_PhoneText" class="group2 group2_Phone" />
            <br/>
            <input type="radio" id="group2_EMail" name="group2"/>
            <label for="group2_EMail">E-Mail:</label>
            <input type="text" name="group2_EMailText" class="group2 group2_EMail" />
            <br/>                
            <input type="radio" id="group2_USMail" name="group2"/>
            <label for="group2_USMail">US Mail:</label>
            <input type="text" name="group2_USMailText" class="group2 group2_USMail" />
        </span>
    </fieldset>
    <div>
        <input type="submit" value="Send" id="submit"/>
    </div>
  </form>
</body>

Let me explain what is going on in the jQuery, using the HTML above:

  • When a radio button's checked state changes, each control with a class name that matches the radio button's name attribute has the required property removed.
  • If a radio button is checked (i.e. checked=true), then each control with a class name that matches the radio button's id attribute has the required property added.
  • Finally, the validator seems to have to be run on a single form control (not on individual text controls like I was doing).

Here is the sample Fiddle that I ended with: Fiddle v8

At tilda: You didn't say much, but what you did say helped a lot!

screen capture

Community
  • 1
  • 1
  • Call `$.validate` once on `$(document).ready`, not all the time. I suggest viewing the [examples](http://jquery.bassistance.de/validate/demo/) carefully. – Ryley Jan 15 '14 at 23:22
  • 1
    Correction: `var radName='group1'; $('.' + radName).validate...` – tilda Jan 16 '14 at 00:17
  • The code works now. I thought jQuery was supposed to be easy? –  Jan 16 '14 at 19:02