Per76
Per76

Reputation: 184

Validate dynamic radio buttons jQuery

Problem: I can´t validate dynamically created radio buttons.

Question: how do I use jQuery to validate the radio buttons?

Is it possible to customise the jQuery to validate dynamically created radio buttons?

Any suggestions?

HTML and PHP from my form

<label class="radio">
    <input type="radio" name='radnummer_varde[<?php echo $kk['radnummer'];?>]' value='1' <?php if (($hamta_formaga['radnummer_varde'] == '1')) echo 'checked="checked" '; ?>>
    <i class="rounded-x"></i>Prövas
</label>

<label class="radio">
    <input type="radio" name='radnummer_varde[<?php echo $kk['radnummer'];?>]' value='0' <?php if (($hamta_formaga['radnummer_varde'] == '0')) echo 'checked="checked" '; ?>>
    <i class="rounded-x"></i>Prövas ej
</label>

echo $kk['radnummer'] is numeric.

Validation via JS

var AbbRedigeraForm = function () {

    return {        

        initAbbRedigeraForm: function () {
            // Validation
            $("#redigera_abb").validate({
                // Regler för validation
                rules:
                {
                    'radnummer_varde[]':
                    {
                        required: true                      
                    },
                    aktiv:
                    {
                        required: true                      
                    },
                    arbetsomrade:
                    {
                        required: true,
                        minlength: 8,
                        maxlength: 30
                    },
                    syfte:
                    {
                        required: true                      
                    },
                    overgripande_mal:
                    {
                        required: true                      
                    },
                    undervisning:
                    {
                        required: true
                    },
                    redovisningsform:
                    {
                        required: true
                    },

                },

                // Messages for form validation
                messages:
                {
                    radnummer_varde:
                    {
                        required: 'Du måste ange detta.'                        
                    },
                    arbetsomrade:
                    {
                        required: 'Skriv en rubrik för arbetsområdet.'
                    },
                    syfte:
                    {
                        required: 'Skriv ett syfte.'                        
                    },
                    overgripande_mal:
                    {
                        required: 'Du måste ange övergripande mål.'
                    },
                    undervisning:
                    {
                        required: 'Du måste skriva något om undervisningen.'
                    },
                    redovisningsform:
                    {
                        required: 'Du måste skriva något om redovisning.'
                    },                  
                },      
                // Do not change code below
                errorPlacement: function(error, element)
                {
                    error.insertAfter(element.parent());
                }
            });
        }

    };

}();

EDIT 2015-03-27:

Option 2

<label class="radio">
    <input type="radio" name='radnummer_varde[<?php echo $kk['radnummer'];?>]' value='1' <?php if (($hamta_formaga['radnummer_varde'] == '1')) echo 'checked="checked" '; ?>>
    <i class="rounded-x"></i>Prövas
</label>

<label class="radio">
    <input type="radio" name='radnummer_varde[<?php echo $kk['radnummer'];?>]' value='0' <?php if (($hamta_formaga['radnummer_varde'] == '0')) echo 'checked="checked" '; ?>>
    <i class="rounded-x"></i>Prövas ej
</label>

<script type="text/javascript"> 
    $(document).ready(function () {
    $('#redigera_abb').validate({});                                
    $('[name="radnummer_varde[<?php echo $kk['radnummer'];?>]"]').rules('add', {
        required: true,
        messages: {
            required: "At least one option needed."
        }
    }); 
    });                             
</script>

Upvotes: 0

Views: 2213

Answers (1)

Sparky
Sparky

Reputation: 98718

"Is it possible to customise the jQuery to validate dynamically created radio buttons?"

Yes, this is no different than adding validation to any dynamically created element.

First, let's examine this part of your code...

var AbbRedigeraForm = function () {

    return {        

        initAbbRedigeraForm: function () {
            // Validation
            $("#redigera_abb").validate({
                // Regler för validation
                rules:
                {
                    'radnummer_varde[]':
                    {
                        required: true                      
                    },
                    ....
  1. You would not normally put .validate() inside of a function. It's not the testing method... .validate() is the initialization method. Therefore, .validate() only goes inside a DOM ready handler where it's called one time to initialize the plugin on your form. Otherwise, validation is not ready when you need it and/or the .validate() method is called repeatedly.

  2. You cannot declare a rule within the rules option of .validate() if you do not have the exact name of the element. Since radnummer_varde[] is not really the actual name, this rule declaration does nothing.

  3. Minor point, but you should never use Allman style code formatting in JavaScript. Why? Because JavaScript uses "Automatic Semicolon Insertion". It also makes the code a little harder to read for people that are familiar with JavaScript's more typical 1TBS format.


Solutions for dynamically created elements...

OPTION 1: Simply include the rule declaration inline with the element, instead of using the rules option within .validate(). For the required rule, you can either use a class or the HTML 5 required attribute as follows...

<input type="radio" name='radnummer_varde[1]' class="required" ...

OR

<input type="radio" name='radnummer_varde[1]' required="required" ...

There are limitations as certain kinds of complex rules need parameters which cannot be set inline. That's where option 2 would be needed.

OPTION 2: Use the plugin's .rules('add') method immediately after you've dynamically created the input elements. (You have not shown how these elements are "dynamically" created.)

// your code that dynamically creates the element

// declare the rule on the new element
$('[name="radnummer_varde[1]"]').rules('add', {
    required: true,
    messages: { // optional
        required: "custom message"
    }
});

OPTION 3: Your elements are not really created "dynamically", but you do not know the exact name in advance. Use a "starts with" selector to grab all of these elements and a jQuery .each() to apply the method to all elements.

$('[name^="radnummer_varde"]').each(function() {
    $(this).rules('add', {
        required: true,
        messages: { // optional
            required: "custom message"
        }
    });
});

NOTES:

  1. NO MATTER how you declare the rules, every input must contain a name attribute.

  2. Usage of .rules() does not negate the usage of the .validate() method. You must have already called .validate() on the form to initialize the plugin before you can call .rules().

  3. If the selector attached to .rules() targets a group of elements at once, then you must use a jQuery .each() function or the plugin will only use the first matched element.


"how do I use jQuery to validate the radio buttons?"

I noticed that your HTML for the radio button might contain checked="checked" under certain conditions. Just be aware that if the radio button loads into the page as checked, then there is nothing for validation to do, because the required rule is already satisfied.

Upvotes: 3

Related Questions