【问题标题】:Is there a jQuery plugin for conditionally disabling forms (not submit)?是否有用于有条件地禁用表单(不提交)的 jQuery 插件?
【发布时间】:2012-08-01 21:07:46
【问题描述】:

我正在使用 jQuery 1.7.2。

我不想阻止表单提交。我想模拟所有输入的禁用属性。可能会添加和删除此属性。

我有一个输入并提交的表单:

<form name="login" id="login" method="post" action="">
    <label>Password</label>
    <input class="text" id="password" name="password" />
    <button type="submit">Login</button>
</form>

在页面下方有另一个表单,除非填写了登录表单,否则我想阻止它。

<form id="form" method="post" action="">
    <label>Enter Phone Number</label>
    <input id="areacode" name="areacode" maxlength="3" class="required number" type="text" pattern="[0-9]*" />
    <input id="phoneone" name="phoneone" maxlength="3" class="required number" type="text" pattern="[0-9]*" />
    <input id="phonetwo" name="phonetwo" maxlength="4" class="required number" type="text" pattern="[0-9]*" />
    <button id="phone_submit" type="submit">Next</button>
</form>

现在我想阻止用户填写此表单,而不是提交。如果他们禁用 javascript 等,后端将阻止它。后端还在有效提交时将“只读”属性发送回第一个表单的输入字段。

所以 jQuery 基本上可以查看第一个表单输入是否是只读的,如果不是,则禁用另一个表单。我不想隐藏它,我只想禁用所有字段和按钮。

我认为必须已经有一个插件可以做这样的事情,或者一个 jquery 函数至少可以检查第一个表单的输入字段。到目前为止,我有:

<script type="text/javascript">
    $(window).load(function(){
        if $('#password').attr('readonly',true){
            $('#areacode').attr('disabled',true);
            $('#phoneone').attr('disabled',true);
            $('#phonetwo').attr('disabled',true);
            $('#phone_submit').attr('disabled',true);
    };
</script>

【问题讨论】:

    标签: jquery jquery-plugins


    【解决方案1】:

    我使用一个简单的 if 语句并显示和隐藏覆盖来做到这一点。我首先添加了一个 disabled 属性,但我想要叠加层,因此两种方式都没有意义。

    不像某些人想要的那样语义化,但它工作得很好。为了便于阅读,下面的代码是内联样式。

    太好了....html:

    <form>
        <input id="password" type="text" />
        <button type="submit">Submit</button>
    </form>
    <fieldset style="position: relative;">
        <div class="overlay" style="width:100%;height:100%; position: absolute; top:0; left:0; background: rgba(0,0,0,0.5); color: #fff;">You must fill out the password above.</div>
        <form></form>
    </fieldset>
    

    js:

    <script type="text/javascript">
        $(document).ready(function() {
            var block = false;
            if ($('#password').attr('readonly')) {
                block = false;
            } else {
                block = true;
            }
            if (block) {
                $('.overlay').css('display','block');
            }
        });
    </script>
    

    现在,当后端将密码设置为只读时,您可以使用字段集中的表单。如果 #password 输入上没有 readonly 属性,则该表单被有效阻止。当然,与往常一样,有后端代码阻止表单提交,以防有人决定用 firebug 或其他东西擦除覆盖。

    感谢您的帮助。

    【讨论】:

      【解决方案2】:

      我尝试了一些新的表单处理方式,有点类似,但您不希望显示或隐藏基于其他字段的元素。 幸运的是,因为我很懒,要改变它的行为你只需要改变 2 行代码。

      它仍然非常基础,没有经过适当的测试,但你可以在我的网站上找到源代码 http://geuze.name/html5form/html5form.relate.js(更改第 125 和 127 行)

      还有一个快速演示以及我在http://geuze.name/html5form/上的html5form polyfill

      即使不是您所需要的,代码也可能只是帮助您朝着正确的方向思考。

      编辑 添加代码,因为显然是惰性服务器;)

      /*
       *  Form Relationship Plugin - jQuery plugin
       *  Version 0.2
       * 
       * Built for the jQuery library
       * http://jquery.com
       * 
       * Plugin allows you to easily add smart relations between form fields and other elements
       * 
       *
       */
      
      (function($){
          $.fn.relate = function(options){
              // Uncomment string below during testing
              "use strict";
              var tmp = {},
              // Default configuration properties
                  defaults = {
                      scoreRequired: 1,
                      scoreOnTrue: 1,
                      scoreOnFalse: 0,
                      globalScope: true,
                      debug: false
                  },
                  callbacks = {
                      oninitialize:  function(){},// Runs once per form
                      onfinish:      function(){}// Runs once after no errors
                  },
                  opts = $.extend(
                          {},
                          defaults,
                          callbacks,
                          options
                  );
              // Force debug false on sucky browsers
              if(typeof(console)  === 'undefined' || typeof(console.info)  === 'undefined'){
                  opts.debug = false;
              }
              // Our debug output
              function debug(str){
                  if(opts.debug === true){
                      console.info(str);
                  }
              };
              // Helper function to determine object size
              function objSize(obj) {
                  var size = 0, key;
                  for (key in obj) {
                      if (obj.hasOwnProperty(key)) size++;
                  }
                  return size;
              };
      
              // Update per element
              // Easier would be to always loop over everything, but I assume this is faster
              function update(form){
                  var related,
                      currentScore = 0,
                      scoreOnTrue = 1,
                      scoreOnFalse = 0;
      
                  // Reset score
                  $('[data-currentscore]').removeAttr('data-currentscore');
                  // Loop all possible smart elements
                  $('select[data-relate], select:has(option[data-relate]), input[data-relate], textarea[data-relate]', form).each(function(){
                      if($(this).is('select')){
                          $('option', this).each(function(){
                              // Find relation
                              related = $(this).attr('data-relate');
                              // If no relation, no points to anything
                              if(!related || related.length  0 ? $(this).attr('data-scoreontrue') * 1 : opts.scoreOnTrue;
                              scoreOnFalse = $(this).filter('[data-scoreonfalse]').length > 0 ? $(this).attr('data-scoreonfalse') * 1 : opts.scoreOnFalse;
                              if($(this).is(':selected')){
                                  $(related).each(function(){
                                      currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                      $(this).attr('data-currentscore', currentScore + scoreOnTrue);
                                  });
                              } else {
                                  $(related).each(function(){
                                      currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                      $(this).attr('data-currentscore', currentScore - scoreOnFalse);
                                  });
                              }
                          });
                      } else {
                          // Find relation
                          related = $(this).attr('data-relate');
                          // If no relation, no points to anything
                          if(!related ||related.length  0  ? $(this).attr('data-scoreontrue') * 1 : opts.scoreOnTrue;
                          scoreOnFalse = $(this).filter('[data-scoreonfalse]').length > 0  ? $(this).attr('data-scoreonfalse') * 1 : opts.scoreOnFalse;
                          if($(this).is('input:radio') || $(this).is('input:checkbox')){
                              if($(this).is(':checked')){
                                  $(related).each(function(){
                                      currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                      $(this).attr('data-currentscore', currentScore + scoreOnTrue);
                                  });
                              } else {
                                  $(related).each(function(){
                                      currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                      $(this).attr('data-currentscore', currentScore + scoreOnFalse);
                                  });
                              }
                          } else if($(this).val() !== '' && $(this).val() != $(this).attr('placeholder')){
                              $(related).each(function(){
                                  currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                  $(this).attr('data-currentscore', currentScore + scoreOnTrue);
                              });
                          } else {
                              $(related).each(function(){
                                  currentScore = $(this).filter('[data-currentscore]').length > 0 ? $(this).attr('data-currentscore') * 1 : 0;
                                  $(this).attr('data-currentscore', currentScore + scoreOnFalse);
                              });
                          }
                      }
                  });
                  // Finaly loop over all fields with some sort of score
                  $('[data-currentscore]').each(function(){
                      var scoreRequired = $(this).has('[data-scorerequired]') ? $(this).attr('data-scorerequired') * 1 : opts.scoreRequired;
                      if($(this).attr('data-currentscore') * 1 >= scoreRequired * 1){
                          $(this).show();
                      } else {
                          $(this).hide();
                      }
                  });
      
              };
      
              // Loop over all forms requested
              this.each(function(){
                  // Private properties
                  var form = $(this);
      
                  // Init / change / keyup(fixes some browsers on select)
                  update(form);
                  $('select[data-relate], select:has(option[data-relate]), input[data-relate], textarea[data-relate]')
                  .change(function(){
                      update(form);
                  }).keyup(function(){
                      update(form);
                  });
              });
              return this;
          }
      })(jQuery);
      

      用法如下: $('form').relate({...}); 和一些html数据属性

      【讨论】:

      • 有趣,从任何地方访问我的网站都没有问题。我会将代码粘贴到我的消息中。但是有点长。
      • 我现在可以查看链接了。也许今天早些时候只是间歇性的问题。
      【解决方案3】:

      或者,您可以使用以下方法实现此目的:

      $('#divID').modal().show();
      $('#divID').modal().close();
      

      http://www.ericmmartin.com/projects/simplemodal/

      【讨论】:

      • 我不能把它放在一个模态中。不过,感谢您的建议。
      猜你喜欢
      • 2010-09-18
      • 1970-01-01
      • 2011-09-29
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多