取消JQuery验证表单

时间:2017-01-02 19:42:17

标签: javascript forms jquery-validate

我试图在表单中弹出取消按钮,但单击取消按钮时会提交表单。

如何:从元素中删除验证,取消绑定侦听器,或为我的表单设置特定事件以便在单击取消按钮时不提交?

感谢您的帮助

var form = document.createElement('form')
form.className = 'feedback_form corner_style'
form.remove = function() {this.parentElement.removeChild(this)}

var label = document.createElement('label')
label.innerHTML = 'Why did this not satisfy your need?'
form.appendChild(label)
form.appendChild(document.createElement('br'))

var textarea = document.createElement('textarea')
textarea.rows = 10
textarea.cols = 50
textarea.name = 'feedback'
form.appendChild(textarea)
form.appendChild(document.createElement('br'))

var submit = document.createElement('input')
submit.innerHTML = 'Submit'
submit.name = 'submit'
submit.type = 'submit'
form.appendChild(submit)

var cancel = document.createElement('button')
cancel.innerHTML = 'Cancel'
cancel.addEventListener('click', () => {
  console.log('remove form')
  form.preventDefault()
  console.log('check 1 ')
  form.remove()
})
form.appendChild(cancel)

document.body.appendChild(form)
$(form).validate({
  debug: true,
  rules: {
    feedback: 'required'
  },
  submitHandler: () => {
    console.log('submit not_satisfied')
    $.ajax({
      url: '/not_satisfied',
      cache: false,
      data: {
        id: JSON.parse(row.dataset.extra_columns).id,
        feedback: 'NotImplimented'
      },
      error: (jqXHR, textStatus, errorThrown) => {
          console.log(String(jqXHR))
          console.log(String(textStatus))
          console.log(String(errorThrown))
          alert('Error processing request.')
      },
      success: data => {
        if (! data) alert('Could not complete request.')
      },
      complete: () => {document.dispatchEvent(new Event('only_nest_form_Submit_Complete'))}
    })
    form.remove()
  }
})

1 个答案:

答案 0 :(得分:0)

可能很明显,但我只需要将取消按钮类型设置为“按钮”。 How to prevent buttons from submitting forms

还有jquery验证的destroy方法尚未记录。 https://github.com/jzaefferer/jquery-validation/issues/1912

我遇到了破坏问题,因为它导致我的页面重新加载,但是在jsfiddle上页面不会重新加载所以要小心。