This question may also be titled: “Use javascript to set field required?”
<form class="theform" action="#" method="post" name="theform">
<label for="tname">Team Name:</label>
<input type="text" placeholder="Bears" required /><br>
<label for="captain">Captain:</label>
<input type="text" placeholder="Captain's Name" required /><br>
<button type="submit" value="Submit" onclick="toggleReq()" >Submit</button>
</form>
This is a highly simplified version of my form. I know this may seem odd, but I want the form to actually submit with the “Captain” field empty and set as required.
I was thinking that this might–just might–be possible by having javascript remove the required attribute when the submit button is clicked–hence the onclick="toggleReq()".
Since everyone wants to know why this would ever be useful, I’ll explain:
The concept was introduced some time ago that spammers could be foiled by including an extra form field that users were instructed to leave empty. (Ideally this field would be hidden; real users don’t need to know it exists.) It would be evident which comments came from spambots because the spambot would have automatically filled the dummy-field.
There are a couple weaknesses to that approach that I am seeking to address. A spambot could potentially ignore a non-required field. However, simply making the dummy-field required would prevent the form from being submitted by real users. So, the best bet at catching bots is to have the input field required but to have that required tag ignored. Ignoring isn’t technically possible, but switching off the required attribute is.
If you id the captain’s name field it’s pretty easy. Assuming an id of “captain”:
Or the non jQuery version:
Of course, if you want a true “toggle” you will need to read the current state first.