最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - jQuery.validate and hidden input - Stack Overflow

programmeradmin0浏览0评论

I have a form with a pseudo-select element. The pseudo-select element is a dropdown menu. When one of the dropdown items is clicked, a hidden input is given a value assigned to that item. I'm using jQuery.validate to validate the form. A simple validation rule is bound to the hidden input. If the input has no value, the hidden input and the pseudo-select are given an error class and an error message shows.

My problem is that changing the value of a hidden input does not trigger change, keyup, or blur events. If the error state is applied to the hidden input, that state remains after the input is given a valid value. Only when the form is again submitted is the input correctly validated.

Since jQuery.validate enables validation on hidden inputs, I'm wondering if there's a configuration or method that handles this issue.

EDIT:

$form.validate({
    ignore: false,
    rules: {
        'firstname': 'required',
        'lastname': 'required',
        'org': 'required',
        'role': 'required',
        'email': {
            required: true,
            email: true
        }
    },
    messages: {
        'firstname': 'Please enter your first name',
        'lastname': 'Please enter your last name',
        'org': 'Please enter your organization',
        'role': 'Please select your role',
        'email': 'Please enter your email'
    },
    errorPlacement: function(error, element) {
        var $errMessage = $('.js-err-message');

        $errMessage.removeClass('js-hidden'); 

        $(error).each(function(){
            $errMessage.append(error);

            if (element.is('#role-input')) {
                $('.pseudo-select').addClass('mad-error');
            }
        });

    }
});

I have a form with a pseudo-select element. The pseudo-select element is a dropdown menu. When one of the dropdown items is clicked, a hidden input is given a value assigned to that item. I'm using jQuery.validate to validate the form. A simple validation rule is bound to the hidden input. If the input has no value, the hidden input and the pseudo-select are given an error class and an error message shows.

My problem is that changing the value of a hidden input does not trigger change, keyup, or blur events. If the error state is applied to the hidden input, that state remains after the input is given a valid value. Only when the form is again submitted is the input correctly validated.

Since jQuery.validate enables validation on hidden inputs, I'm wondering if there's a configuration or method that handles this issue.

EDIT:

$form.validate({
    ignore: false,
    rules: {
        'firstname': 'required',
        'lastname': 'required',
        'org': 'required',
        'role': 'required',
        'email': {
            required: true,
            email: true
        }
    },
    messages: {
        'firstname': 'Please enter your first name',
        'lastname': 'Please enter your last name',
        'org': 'Please enter your organization',
        'role': 'Please select your role',
        'email': 'Please enter your email'
    },
    errorPlacement: function(error, element) {
        var $errMessage = $('.js-err-message');

        $errMessage.removeClass('js-hidden'); 

        $(error).each(function(){
            $errMessage.append(error);

            if (element.is('#role-input')) {
                $('.pseudo-select').addClass('mad-error');
            }
        });

    }
});
Share Improve this question edited Dec 2, 2014 at 14:20 maxhallinan asked Dec 1, 2014 at 15:33 maxhallinanmaxhallinan 1,3392 gold badges14 silver badges29 bronze badges 3
  • 1 You'd have better to post all relevant code in question – A. Wolff Commented Dec 1, 2014 at 15:39
  • Sorry, I didn't think the code was strictly relevant. My question is about the capabilities of jQuery.validate in general and not about a problem with my code. – maxhallinan Commented Dec 2, 2014 at 15:06
  • Relevant code would include any code required to reproduce the issue. In your case, it saves people time when they create a demo for their answer. It also helps future readers better understand the problem/solution if they're having a similar issue. Thanks. – Sparky Commented Dec 2, 2014 at 23:38
Add a ment  | 

1 Answer 1

Reset to default 9

Using the jQuery Validation plugin, these are the standard events that will trigger validation on a particular element (the last one is a bit different)...

  • typing in a box
  • selecting from a list
  • clicking a checkbox or radio button
  • losing focus of the input element
  • clicking the submit button (entire form is validated)

Since none of those things are triggered when a hidden element changes value, you'll need to trigger it yourself by using the .valid() method to validate the element.

You've shown us no code whatsoever, let alone the code that changes the value of the hidden element, so I can only give you something generic. You could place the .valid() code within whatever function you use to change the value...

  • change the value of the hidden element
  • call .valid() to validate the hidden element

    $(document).ready(function() {
    
        $('#myform').validate({  // initialize plugin
            // your options
        });
    
        $('#some_button').on('click', function() {
            // some imaginary button that changes the hidden value
            $('input[name="myHiddenElement"]').val('newvalue');  // <- change the hidden value
            $('input[name="myHiddenElement"]').valid();  // <- triggers validation on the hidden element
        });
    
    });
    

You will likely need to use other plugin options like the errorPlacement option to properly place the error message label within your layout, otherwise it will float someplace after the hidden element.

发布评论

评论列表(0)

  1. 暂无评论
ok 不同模板 switch ($forum['model']) { /*case '0': include _include(APP_PATH . 'view/htm/read.htm'); break;*/ default: include _include(theme_load('read', $fid)); break; } } break; case '10': // 主题外链 / thread external link http_location(htmlspecialchars_decode(trim($thread['description']))); break; case '11': // 单页 / single page $attachlist = array(); $imagelist = array(); $thread['filelist'] = array(); $threadlist = NULL; $thread['files'] > 0 and list($attachlist, $imagelist, $thread['filelist']) = well_attach_find_by_tid($tid); $data = data_read_cache($tid); empty($data) and message(-1, lang('data_malformation')); $tidlist = $forum['threads'] ? page_find_by_fid($fid, $page, $pagesize) : NULL; if ($tidlist) { $tidarr = arrlist_values($tidlist, 'tid'); $threadlist = well_thread_find($tidarr, $pagesize); // 按之前tidlist排序 $threadlist = array2_sort_key($threadlist, $tidlist, 'tid'); } $allowpost = forum_access_user($fid, $gid, 'allowpost'); $allowupdate = forum_access_mod($fid, $gid, 'allowupdate'); $allowdelete = forum_access_mod($fid, $gid, 'allowdelete'); $access = array('allowpost' => $allowpost, 'allowupdate' => $allowupdate, 'allowdelete' => $allowdelete); $header['title'] = $thread['subject']; $header['mobile_link'] = $thread['url']; $header['keywords'] = $thread['keyword'] ? $thread['keyword'] : $thread['subject']; $header['description'] = $thread['description'] ? $thread['description'] : $thread['brief']; $_SESSION['fid'] = $fid; if ($ajax) { empty($conf['api_on']) and message(0, lang('closed')); $apilist['header'] = $header; $apilist['extra'] = $extra; $apilist['access'] = $access; $apilist['thread'] = well_thread_safe_info($thread); $apilist['thread_data'] = $data; $apilist['forum'] = $forum; $apilist['imagelist'] = $imagelist; $apilist['filelist'] = $thread['filelist']; $apilist['threadlist'] = $threadlist; message(0, $apilist); } else { include _include(theme_load('single_page', $fid)); } break; default: message(-1, lang('data_malformation')); break; } ?>