0

如果字段集中有一个 .bad 类的 div,那么禁用按钮的最佳方法是什么?

HTML 示例:

<fieldset>
  <div class="item>
    <label><span>First Name</span>
      <input type="text" name="firstName" placeholder="First" required>
    </label>
  </div>
  <!--adds .bad to parent when input doesn't validate -->
  <div class="item bad">
    <label><span>Last Name</span>
      <input type="text" name="lastName" placeholder="Last" required>
    </label>
    <!-- .alert only present if doesn't validate -->
    <div class="alert">field is required</div>
  </div>
  <input type="button" class="prev button" value="Previous">
  <!-- "disabled" because .bad is present in parent container of Last Name -->
  <input type="button" class="next button" value="Next" disabled>
</fieldset>

已修改并应用于此示例的最佳方法和答案:jQuery 示例:

    // Bind to the 'change' event of the required input elements
$('input[required]').change(function () {
  // cache the value:
  var v = this.value;
  /* Look for the closest 'div.item',
    if the length of the trimmed value is equal to 0 we add 'bad' class,
    if it's not 0 we remove the 'bad' class:*/
  $(this).closest('div.item')[$.trim(v).length === 0 ? 'addClass' : 'removeClass']('bad');
  /* we find the 'input' elements with 'type="button"',
    and set their disabled property according to whether,
    or not, there's a 'div.bad' contained within the 'fieldset' element: */
  $('input[type="button"].next').prop('disabled', function () {
    return $(this).closest('fieldset').find('div.bad').length > 0;
  });
  // We then trigger the 'change' event to disable the buttons if necessary:
}).change();

在这里可以看到大卫的一个工作小提琴:http: //jsfiddle.net/davidThomas/mwkAt/

4

2 回答 2

1

While you've already accepted another answer (at the time of my writing this answer), the way I'd probably approach this is as follows:

// Bind to the 'change' event of the required input elements:
$('input[required]').change(function(){
    // cache the value:
    var v = this.value;

    /* Look for the closest 'div.item',
       if the length of the trimmed value is equal to 0 we add 'bad' class,
       if it's not 0 we remove the 'bad' class:
    */
    $(this).closest('div.item')[$.trim(v).length === 0 ? 'addClass' : 'removeClass']('bad');

    /* we find the 'input' elements with 'type="button"',
       and set their disabled property according to whether,
       or not, there's a 'div.bad' contained within the 'fieldset' element:
    */
    $('input[type="button"].next').prop('disabled', function(){
        return $(this).closest('fieldset').find('div.bad').length > 0;
    });
// We then trigger the 'change' event to disable the buttons if necessary:
}).change();

JS Fiddle demo.

References:

于 2013-10-11T23:18:36.327 回答
1

尝试这个 :

function check(){
        if($('fieldset .bad').length){
          $('#submit_butn_ID').attr('disabled',true)
        }
}
    $('#myform_ID').change(check())

要不就

check()

这是如何工作的。:

1-我们监听表单的变化。

2-如果.bad任何字段集中有任何字段,那么我们将属性 disabled 添加到按钮

于 2013-10-11T22:09:40.460 回答