简体   繁体   中英

Validate dynamic input form elements using Validator Plugin Jquery

I am using this http://jqueryvalidation.org/ jquery validation plugin.

HTML dynamic form will be like this

<form name="baby_book" id="baby_book">
<input name="form_elements[16]" id="form_elements[16]">
<input name="form_elements[17]" id="form_elements[17]">
<input name="form_elements[18]" id="form_elements[18]">

<a class="myfont baby_book_save" href="javascript:void(0)"  onclick="validatefilesizeform('save')" >Save</a> 
</form>

My JS Code will be like this

<script type="text/javascript">
var validator="";

$(document).ready(function(){

var max_length_rules= <?php echo json_encode($valid_rules); ?>;

validator=$("#baby_book").validate();

     $.each(max_length_rules,function(k,v){

             $.each(v, function(key, value){

                   $('input[id="'+key+'"]').rules('add',"required"); 
                });
        });

});

function validatefilesizeform(type)
{
    if(type == 'save')
     {
         document.baby_book.sec_submit.value="save";

         if(validator.form())
         {
            document.baby_book.submit();
         }
    }

</script>

While applying dynamic rules like that it doesn't validate the form.

In console it displays this error

Uncaught TypeError: Cannot read property 'form' of undefined

Can anyone help me how to add dyanmic rules . Thanks.

That's because when the browser finds the validatefilesizeform('save') in the onclick attribute, it evaluates that expression, ie runs the function. With this syntax you're asigning the result of that evaluation to the onclick event, which is not what you want.

The Cannot read property 'form' of undefined error happens because in that moment the $(document).ready() callback has not yet been executed, and, when the function tries to execute validator.form() , that variable is already undefined. It will be initialized later, inside the $(document).ready() .

To get the expected behavior, and avoid the error, you must change the onclick handler to this one:

`onclick="function() { validatefilesizeform('save') }"`

In this case you're registering a function as the value for the onclick attribute. And this function will be evaluated when the control is clicked.

To make it even more clear:

// This is the value returned by the function evaluation:
validatefilesizeform('save')

// This is a function
function() { validatefilesizeform('save'); }

So the second is a function that can be evaluated. The first one evaluates the function. Handlers should always be functions, and not values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM