填写表单字段后启用提交按钮

时间:2021-06-13 19:08:25

标签: javascript html forms toggle submit

我使用 html 创建了这个带有文本框、复选框、选择选项列表和提交按钮的简单表单。默认提交按钮是禁用的。用户填写所有文本框并从选择框中选择一个选项并选中复选框后,必须启用提交按钮。我该如何处理 java 脚本。谢谢你。 这是我的代码,

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>

<form>
    <input type="text" id="u-name" name="username" placeholder="Username" /><br/><br>
    <input type="text" id="u-age" name="age" placeholder="Age" /><br/><br>
    <select id="u-type">
        <option>Choose</option>
        <option>Type 1</option>
        <option>Type 2</option>
        <option>Type 3</option>
    </select> <br> <br>
    <label class='checkbox-inline'>
       <input type='checkbox' name='c-box' id='c-box'>Check Me
    </label>
    <br>
    <input type="submit" id="Save" value="Save" disabled />
</form>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

您必须跟踪每个输入的状态。当所有输入都填写有效数据时,提交按钮将被启用。

像这样:

const submitBtn = document.getElementById('Save')

const uName = document.getElementById('u-name')
const uAge = document.getElementById('u-age')
const uType = document.getElementById('u-type')
const cBox = document.getElementById('c-box')

// run this function whenever the values of any of the above 4 inputs change.
// this is to check if the input for all 4 is valid.  if so, enable submitBtn.
// otherwise, disable it.
const checkEnableButton = () => {
  submitBtn.disabled = !(
      uName.value && 
      uAge.value && 
      cBox.checked &&
      uType.value !== 'Choose'
   )
}

uName.addEventListener('change', checkEnableButton)
uAge.addEventListener('change', checkEnableButton)
uType.addEventListener('change', checkEnableButton)
cBox.addEventListener('change', checkEnableButton)
<!DOCTYPE html>
<html>

<head>
  <title></title>
</head>

<body>

  <form>
    <input type="text" id="u-name" name="username" placeholder="Username" />
    <br><br>
    <input type="text" id="u-age" name="age" placeholder="Age" /><br/><br>
    <select id="u-type">
      <option>Choose</option>
      <option>Type 1</option>
      <option>Type 2</option>
      <option>Type 3</option>
    </select>
    <br><br>
    <label class='checkbox-inline'>
       <input type='checkbox' name='c-box' id='c-box'>Check Me
    </label>
    <br>
    <input type="submit" id="Save" value="Save" disabled />
  </form>
</body>

</html>