Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Checkboxes - At Least 1 is Selected? 1

Status
Not open for further replies.

damipera

Technical User
Dec 1, 2005
134
GB
Hi guys,

I have this checkboxes:

<input name="BookBox" id="BookBox" type="checkbox" value="12" />Assess
<input name="BookBox" id="BookBox" type="checkbox" value="14" />Communication
<input name="BookBox" id="BookBox" type="checkbox" value="4" />Family
<input name="BookBox" id="BookBox" type="checkbox" value="3" />Document
<input name="BookBox" id="BookBox" type="checkbox" value="6" />Computer

How do you make the visitor to click/check at least one box before submitting the form?

Thanks for any ideas.
 
Hi

For example by calling [tt]onsubmit[/tt] a function like this :
JavaScript:
[b]function[/b] [COLOR=orange]checkCheckbox[/color][teal]([/teal]event[teal])[/teal]
[teal]{[/teal]
  [b]if[/b] [teal](![/teal] Array[teal].[/teal][COLOR=orange]from[/color][teal]([/teal]document[teal].[/teal][COLOR=orange]querySelectorAll[/color][teal]([/teal][i][green]'input[name="BookBox"]'[/green][/i][teal])).[/teal][COLOR=orange]filter[/color][teal]([/teal]i [teal]=>[/teal] i[teal].[/teal]checked[teal]).[/teal]length[teal]) {[/teal]
    event[teal].[/teal][COLOR=orange]preventDefault[/color][teal]()[/teal]
    [COLOR=orange]alert[/color][teal]([/teal][i][green]'At least one checkbox must be checked'[/green][/i][teal])[/teal]
  [teal]}[/teal]
[teal]}[/teal]
[ul]
[li]See it in action at [/li]
[li]Used just ECMAScript 6, no library.[/li]
[li]To keep it simple, this checks all inputs with [tt]name[/tt] "BookBox", regardless whether they are checkboxes or not or belong to the form about to submit or not.
Just change the [tt].querySelectorAll()[/tt] call to [tt]event[teal].[/teal]target[teal].[/teal]querySelectorAll[teal]([/teal][green]'input[type="checkbox"][name="BookBox"]'[/green][teal])[/teal][/tt] to restrict it to checkboxes in the submitted form.
[/li]
[li]Note that [tt]id[/tt] must be unique per document. Using the same [tt]id[/tt] for multiple elements like in your original code, may cause weird behavior later.[/li]
[/ul]


Feherke.
feherke.github.io
 
Thanks feherke ..Thats awesome! Have a good day.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top