Submit form only if at least one checkbox is checked

后端 未结 8 2084
梦如初夏
梦如初夏 2021-01-06 18:42

i\'m triyng to validate a form. In this form you\'ve to choose at least one element by checkboxes, and I can\'t be sure about their quantity (it depends by elements number).

8条回答
  •  心在旅途
    2021-01-06 19:11

    The easiest method would be with javascript, fortunately someone's already done all the work here (with jQuery). All you'd need to do to adapt that example is to change #form_check to #booking.

    Essentially what that example is doing is forcing itself before the submit action when it sees one is being tried for the form then it's searching inside the form element for any checkbox elements with a checked state and if it can't find any is sending a preventdefault to stop whatever the client/browser's default response to a submit action request would be or otherwise just sending as normal.

    Also regarding the other answers, using === is more secure and returning false gives you some redundancy. Here's some discussion on what the return false adds.

    Additionally don't use click() for this as you potentially run into use cases where you're technically submitting the form but aren't actually clicking it, like say when you hit enter

提交回复
热议问题