如何在表单无效时禁用按钮?

时间:2016-10-29 09:52:46

标签: javascript html5 polymer polymer-1.0

我有一个自定义元素,基本上包含电子邮件和密码表单,

如果没有填写电子邮件或密码,有没有办法禁用按钮?

请在下面找到我的元素:

      <paper-dialog id="dialog">
    <h2>Login</h2>

      <paper-input id="zumbuza" type="email" is="iron-input" label="Email" type="text" bind-value="{{user.email}}" auto-validate  error-message="Auto v"></paper-input>


    <paper-input-container>
       <label>Passwrod</label>
       <input  is="iron-input" type="password" bind-value="{{user.password}}"></input>
    </paper-input-container>

    <paper-button toggles raised active class="colorful">Submit</paper-button>

  </paper-dialog>

2 个答案:

答案 0 :(得分:1)

我知道验证的最简单方法是表单。 Polymer有一个名为“iron-form”的自定义元素。它上面有一个演示:https://elements.polymer-project.org/elements/iron-form?view=demo:demo/index.html&active=iron-form

下面的代码是从那里直接复制粘贴。看看那个,我想你会明白的。

<form is="iron-form" method="get" action="/" id="eventsDemo">
  <paper-input name="name" label="Name" required auto-validate></paper-input>
  <paper-input name="password" label="Password" type="password" required auto-validate></paper-input>
  <paper-checkbox name="read" required>You must check this box</paper-checkbox><br>
  <paper-button raised onclick="_delayedSubmit(event)" disabled id="eventsDemoSubmit">
    <paper-spinner id="spinner" hidden></paper-spinner>Submit</paper-button>
  <paper-button raised onclick="_reset(event)">Reset</paper-button>
  <div class="output"></div>
</form>
<script>
  eventsDemo.addEventListener('change', function(event) {
    // Validate the entire form to see if we should enable the `Submit` button.
    eventsDemoSubmit.disabled = !eventsDemo.validate();
  });
  function _delayedSubmit(event) {
    spinner.active = true;
    spinner.hidden = false;
    eventsDemoSubmit.disabled = true;
    // Simulate a slow server response.
    setTimeout(function() {
      Polymer.dom(event).localTarget.parentElement.submit();
    }, 1000);
  }
  function _reset(event) {
    var form = Polymer.dom(event).localTarget.parentElement
    form.reset();
    form.querySelector('.output').innerHTML = '';
  }
  document.getElementById('eventsDemo').addEventListener('iron-form-submit', function(event) {
    spinner.active = false;
    spinner.hidden = true;
    eventsDemoSubmit.disabled = false;
    this.querySelector('.output').innerHTML = JSON.stringify(event.detail);
  });
</script>

答案 1 :(得分:0)

您可以使用js

尝试此操作
    $(".submit-name").attr("disabled", "true");
    $(".control-name").blur(function(){
        if ($(this).val() != "") {
            $(".submit-name").removeAttr("disabled");
        } else {
            $(".submit-name").attr("disabled", "true");        
        }
    });