godzillante February 2016

html5 "required" attribute for mixed radio/text

I'm designing a form which has, among others, the following elements:

<div>
    <div class="radio-list">
        <label><input type="radio" name="ftp_directory" id="ftpdir_public_html" value="public_html"> <strong>public_html</strong> directory</label>
        <label><input type="radio" name="ftp_directory" id="ftpdir_blank" value="."> <strong>Root</strong> directory </label>
        <label><input type="radio" id="ftpdir_custom" value=""> Other directory (please specify)</label>
    </div>
    <input name="ftp_directory" class="form-control" type="text" disabled="disabled" aria-disabled="true">
</div>

I enable the latter <input> text element when I check the 3rd radio (via jQuery) and all is fine.

What I want to do is set up the required attribute in a correct way so that it vaildates if any of the first two radio button is checked or the 3rd radio is checked and the input has some text.

Note: I know I can do it with some JS/jQuery validation code but I'd like to do it in pure HTML5.

Answers


godzillante February 2016

I solved via jQuery, as said it is not possible with HTML5 only.

Here's my solution:

$(document).on('change', 'input[type="radio"][name="ftp_directory"]', function(e){
    var radio_id = $(this).attr('id');
    if (radio_id == 'ftpdir_custom')
    {
        $('#ftp_directory_custom').prop('disabled', false);
        $('#ftp_directory_custom').prop('required', true);
        $('input[type="radio"][name="ftp_directory"]').removeProp('required').removeAttr('aria-required');
    }
    else
    {
        $('#ftp_directory_custom').prop('disabled', true);
        $('#ftp_directory_custom').removeProp('required');
        $('input[type="radio"][name="ftp_directory"]').prop('required', true);
    }
});

The name attribute must be different, anyway, for radio buttons and text input. Plus, because of the latter, one has to detect and differentiate request parameters server-side accordingly. Improvements are welcome.


Boldewyn February 2016

As already said, you cannot do this with radio buttons + text input. However, you can achieve something similar with data lists and a single text field:

<input type="text" name="ftp_directory" list="preselection" required>
<datalist id="preselection">
  <option>public_html</option>
  <option value=".">current directory</option>
</datalist>

Logically, this meets exactly your constraints. However, it might not be stylistically what you're looking for.

Post Status

Asked in February 2016
Viewed 1,824 times
Voted 5
Answered 2 times

Search




Leave an answer