How do I use jQuery to disable a form's submit button until every required field has been filled?

前端 未结 6 1667
故里飘歌
故里飘歌 2021-01-01 08:21

I have a form with multiple inputs, select boxes, and a textarea. I would like to have the submit button be disabled until all of the fields that I designate as required are

6条回答
  •  情书的邮戳
    2021-01-01 08:34

    Start with the button disabled (obviously). Bind an onkeyup event to each required text input, and an onchange or onclick to the select boxes (and any radio buttons/checkboxes), and when it fires, check whether all required inputs are filled. If so, enable the button. If not, disable it.

    There is one loophole here, though. Users can delete the value of a text field without triggering the onkeyup event by using the mouse to "cut" the text out, or by holding down the delete/backspace key once they have deleted it all, and clicking the button before deleting it.

    You can get around the second by either

    • disabling the button with onkeydown and checking if it is ok on onkeyup
    • checking for validity when the button is clicked

提交回复
热议问题