Enable/disable a form element after checking radio button checked states - javascript

I have ten or so questions with radio buttons. They all need to be set to true, before a user can move on to another level. If and only if these ten questions have be answered to true, I'd like to have one of the elements on the form be enabled for further editing. This, I can do on the server side, but don't know how to do it in JavaScript. Any help? Much appreciated. Thanks.
<div>
<label> First Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
<div>
<label> Second Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][researched]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][researched]" type="radio" value="false" />No</label>
</div>
<div>
<label> Third Question:</label>
<label>
<input checked="checked" class="radio_buttons optional pull-right allowed" id="is_complete_and_works_true" name="project[person_attributes][is_complete_and_works]" type="radio" value="true" />Yes</label>
<label >
<input class="radio_buttons optional pull-right allowed" id="is_complete_and_works_false" name="project[person_attributes][is_complete_and_works]" type="radio" value="false" />No</label>
</div>
This code extends to several more of questions.
I've been able to select radios by doing so:
var first_ten = $(':radio[name="project[person_attributes][is_complete_and_works]"][value=true], :radio[name="project[person_attributes][researched]"][value=true], etc…);
Now, I have no idea how to iterate over each and when I click on each radio, whether yes or no, I'd like to see the result for the element to be enabled. Any thoughts much appreciated.

Something like the following will do the job:
<script type="text/javascript">
function proceed(form) {
var el, els = form.getElementsByTagName('input');
var i = els.length;
while (i--) {
el = els[i];
if (el.type == 'checkbox' && !el.checked) {
form.proceedButton.disabled = true;
return;
}
}
form.proceedButton.disabled = false;
}
</script>
<form onclick="proceed(this);">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="submit" name="proceedButton" disabled>
</form>
Note that this is considered bad design as if javascript is not available or enabled, the user can never click the button. Better to deliver the form in a useful state and the, when submitted, use script to validate that the buttons are all checked and cancel the submit if they aren't.
Then at the server you can also check the state and only show the next page if the current one passes validation. If it doesn't, return the user to the first page.
That way neither you or the user care if the script works or not, the page still functions. Of course it might be a better experience if the script does work, but at least the choice isn't binary and it also gives you a simple fallback to support a very wide array of browsers with minimal effort.
So a better solution is:
<form onsubmit="reurn validate(this);" ...>
...
</form>
Then in the function:
function validate(form) {
// if validateion fails, show an appropriate message and return false,
// if it passes, return undefined or true.
}
And always validate at the server since you really have no idea what happened on the client.
Edit
Form controls don't need a name and ID, just use a name. In a radio button set, only one control can be checked, you can't check all of them.
It seems to me that what you are trying to do is to see if at least one radio button has been checked in each set. You can do that based on the code above and selecting each set as you encounter it, e.g.
function validateForm(form) {
// Get all the form controls
var control, controls = form.elements;
var radios = {};
var t, ts;
// Iterate over them
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
// If encounter a radio button in a set that hasn't been visited
if (control.type == 'radio' && !radios.hasOwnProperty(control.name)) {
ts = form[control.name];
radios[control.name] = false;
// Check the set to see if one is checked
for (var j=0, jLen=ts.length; j<jLen; j++) {
if (ts[j].checked) {
radios[control.name] = true;
}
}
}
}
// Return false if any set doesn't have a checked radio
for (var p in radios) {
if (radios.hasOwnProperty(p)) {
if (!radios[p]) {
alert('missing one');
return false;
}
}
}
}
</script>
<form onsubmit="return validateForm(this);">
<input type="radio" name="r0">
<input type="radio" name="r0">
<br>
<input type="radio" name="r1">
<input type="radio" name="r1">
<br>
<input type="reset"><input type="submit">
</form>
Note that your form should include a reset button, particularly when using radio buttons.

Related

addEventListener: click just one element of a bunch of elements

I'm beginner and have trouble with something in JS that might be simple to solve.
I made a quiz based on a NetNinja Udemy course, and I want the submit button to be enabled just when the user clicks on any answer option, and not before, so that he/she can't send a totally empty quiz.
The quiz has 4 questions with 2 options each, and I found this way...
const input_a = document.getElementById("q1a");
const input_b = document.getElementById("q1b");
button.disabled = true;
input_a.addEventListener('click', () => {
button.disabled = false;
});
input_b.addEventListener('click', () => {
button.disabled = false;
});
...to enable the button when the user clicks on any of the two options of the first question (ids: q1a & q1b) Following this logic, there'd also be q2a, q2b, q3a, q3b, q4a & q4b..
As there is a way to include all the answers in one JS element, what should I do in the event function to say "when you click any of this 8 options, enable the button"? Because everything I tried only makes the function work if I click all the buttons, which is obviously impossible in a Quiz .
Thank you! :)
In the solution below, when any of the radio buttons is clicked, the submit button is activated.
let result = [false, false, false, false];
let submitButton = document.getElementById('submitButton');
/* Returns true if all tests have been completed. */
function isValid(){
for(let i = 0 ; i < result.length ; ++i)
if(result[i] != true)
return false;
return true;
}
/* If all tests are completed, the submit button is activated. */
function send(){
result[this.value] = true;
if(isValid()){
submitButton.disabled = false;
console.log("The form can be submitted!");
}
}
/* The send() method is called when the change event of <input> elements whose type is "radio" is fired. */
document.querySelectorAll('input[type="radio"]').forEach((element) => {
element.addEventListener("change", send);
});
<form action="#">
<input type="radio" id="html" name="test1" value="0">
<label for="html">HTML</label><br>
<input type="radio" id="css" name="test1" value="0">
<label for="css">CSS</label><br><br>
<input type="radio" id="js" name="test2" value="1">
<label for="html">JavaScript</label><br>
<input type="radio" id="c#" name="test2" value="1">
<label for="css">C#</label><br><br>
<input type="radio" id="c" name="test3" value="2">
<label for="html">C</label><br>
<input type="radio" id="c++" name="test3" value="2">
<label for="css">C++</label><br><br>
<input type="radio" id="python" name="test4" value="3">
<label for="html">Python</label><br>
<input type="radio" id="ruby" name="test4" value="3">
<label for="css">Ruby</label><br><br>
<button id="submitButton" type="submit" disabled>Submit</button>
</form>

get array of checkboxes checked, and only if seletced in a specific order, then go to URL

First time asking here. I tried a number of topics for this, and I currently use a code for checkboxes, but it's for gathering into a mailform and sending to me via php. I can't seem to find exactly what I need for the following scenario.
I am reworking some Flash puzzles to be all html and javascript (or jquery). One puzzle requires the player to enter a code (to open a safe). In Flash they clicked buttons with code symbols on them, so I thought, Checkboxes displayed as images could work...
I have 9 checkboxes. Each has a value from 1 to 9. In the layout they are mixed up (they are not positioned on the page in sequential order) and I use images to represent the checkboxes.
I want to find out if all the boxes are selected, and if they are selected in the exact order of 1-9.
If the checkboxes are checked in the correct order according to their value (1,2,3,4,5,6,7,8,9) then on clicking the Submit button, the player is taken to the next webpage.
I can also do this with names or Ids, whatever works. Or php. I was hoping to keep it simple, because I am not savvy with the javvy. I probably know enough to be dangerous to myself and others :)
Thanks in advance for any help, or links to a topic that could point me in the right direction.
Here's my html code.
<form name="checklist" method="post" action="My-Page.php">
<label>
<input type="checkbox" value="8">
<img src="btn_8.png"></label>
<label>
<input type="checkbox" value="3">
<img src="btn_3.png"></label>
<label>
<input type="checkbox" value="9">
<img src="btn_9.png"></label>
<label>
<input type="checkbox" value="2">
<img src="btn_2.png"></label>
<label>
<input type="checkbox" value="5">
<img src="btn_5.png"></label>
<label>
<input type="checkbox" value="4">
<img src="btn_4.png"></label>
<label>
<input type="checkbox" value="7">
<img src="btn_7.png"></label>
<label>
<input type="checkbox" value="1">
<img src="btn_1.png"></label>
<label>
<input type="checkbox" value="6">
<img src="btn_6.png"></label>
<input type="submit" value="Open">
</form>
Here's the js I found that gets the values, but I don't know how to make it get the values in that specific order, and then go to a URL, or alert the user to an error.
var array = []
var checkboxes = document.querySelectorAll('input[type=checkbox]:checked')
for (var i = 0; i < checkboxes.length; i++) {
array.push(checkboxes[i].value)
}
Update. I struggled with this, and finally asked a friend to help. What took me 8 days, he did in like 1 hour, from scratch.
I do appreciate those who took time to give me some hints, and this site is great for learning.
As you didn't share code , I will not help you fix it. I can give you some hints and you can try to implement that.
Call onClick function on each checkbox selection.
Create an array and push the selected checkbox's values into it.
// example: checkedArr = [1,2,3,4];
maintain a final order of values with another array
// expectedArr = [1,2,3,4];
Deep compare those 2 arrays and depending on their result, proceed with your business logic.
Comparing two array with their order
var is_same_arr = (checkedArr.length == expectedArr.length) && checkedArr.every(function(element, index) {
return element === expectedArr[index];
});
Here is one way to do it in JavaScript. You maintain a selected array that you either add to or remove items from as the checkboxes are clicked. Then, when the form is submitted, you do a couple checks: first you see if all boxes have been checked. Next, you see if all of the numbers in the selected array are in order.
const form = document.querySelector("#form");
let selected = [];
const numberOfCheckboxes = document.querySelectorAll("#form input").length;
form.addEventListener("click", function(e) {
if (e.target.nodeName !== "INPUT") return;
if (e.target.checked) {
selected.push(parseInt(e.target.value));
} else {
selected = selected.filter(el => el != e.target.value);
}
})
function check(e) {
console.log(selected);
if (selected.length !== numberOfCheckboxes) {
e.preventDefault();
alert("You didn't select all the boxes");
}
const inOrder = selected.every((el, i, arr) => i === 0 || el === arr[i-1] + 1);
if (!inOrder) {
e.preventDefault();
alert("Wrong order!");
}
}
<form id="form" onsubmit="return check(event)">
<label>
<input type="checkbox" value="1" /> 1
</label>
<label>
<input type="checkbox" value="2" /> 2
</label>
<label>
<input type="checkbox" value="3" /> 3
</label>
<button>submit</button>
</form>

How can I have the user click two Terms and Conditions before allowing them to proceed?

I'm trying to make it so that a user has to accept two terms and conditions before being able to click the "Agree and Continue" button. I tried to insert a second checkbox but then the user can just click the "Agree and Continue" button without either box being checked, so this code only has one checkbox.
Thanks!
<SCRIPT language=JavaScript>
<!--
function checkCheckBox(f){
if (f.agree.checked == false )
{
alert('Please check the box to continue.');
return false;
}else
return true;
}
//-->
</SCRIPT>
<form action="https://google.com" method="GET" onsubmit="return checkCheckBox(this)">
<!--Enter your form contents here-->
<input type="checkbox" value="0" name="agree">
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
<br><br>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
<br>
<input type="submit" value="Agree and Continue">
</form>
You can make the checkbox required with:
<form>
<input type="email" required />
<input type="password" required>
<input type="checkbox" required><label for="scales">I'm agree</label>
<input type="submit">
</form>
It will generate:
You don't need any other javascript check, just the 'required' attributes.
Add a second checkbox with an explicit name and then use the boolean "or", ||, to see if both are not checked. The else isn't needed because the first condition returns so it is safe to remove.
function checkCheckBox(f) {
if (!f.agree.checked || !f.agree_third_party.checked) {
alert('Please check the box to continue.');
return false;
}
return true;
}
And alternative is to break it up so that you can give different messages:
function checkCheckBox(f) {
if (!f.agree.checked) {
alert('Please check the first box to continue.');
return false;
}
if (!f.agree_third_party.checked) {
alert('Please check the second box to continue.');
return false;
}
return true;
}
Further, you can completely remove JavaScript and use the native HTML5 required attribute. (I couldn't help wrapping the checkboxes in labels for convenience and accessibility, but they aren't required.)
<label for="agree">
<input type="checkbox" value="0" name="agree" id="agree" required>
<b> I Agree to the Terms and Conditions and Privacy Policy</b>
</label>
<br><br>
<label for="agree_third_party">
<input type="checkbox" value="0" name="agree_third_party" id="agree_third_party" required>
<b> I understand that I am accessing a third-party site and will abide by their Terms and Conditions and Privacy Policy</b><br>
</label>
And if you want to customize the message:
<input type="checkbox" value="0" name="agree" id="agree" required
oninvalid="this.setCustomValidity('You must agree to our terms and conditions.')"
oninput="this.setCustomValidity('')"
>

Problems with checkbox required php-js [duplicate]

When using the newer browsers that support HTML5 (FireFox 4 for example);
and a form field has the attribute required='required';
and the form field is empty/blank;
and the submit button is clicked;
the browsers detects that the "required" field is empty and does not submit the form; instead browser shows a hint asking the user to type text into the field.
Now, instead of a single text field, I have a group of checkboxes, out of which at least one should be checked/selected by the user.
How can I use the HTML5 required attribute on this group of checkboxes?
(Since only one of the checkboxes needs to be checked, I can't put the required attribute on each and every checkbox)
ps. I am using simple_form, if that matters.
UPDATE
Could the HTML 5 multiple attribute be helpful here? Has anyone use it before for doing something similar to my question?
UPDATE
It appears that this feature is not supported by the HTML5 spec: ISSUE-111: What does input.#required mean for #type = checkbox?
(Issue status: Issue has been marked closed without prejudice.)
And here is the explanation.
UPDATE 2
It's an old question, but wanted to clarify that the original intent of the question was to be able to do the above without using Javascript - i.e. using a HTML5 way of doing it. In retrospect, I should've made the "without Javascript" more obvious.
Unfortunately HTML5 does not provide an out-of-the-box way to do that.
However, using jQuery, you can easily control if a checkbox group has at least one checked element.
Consider the following DOM snippet:
<div class="checkbox-group required">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
<input type="checkbox" name="checkbox_name[]">
</div>
You can use this expression:
$('div.checkbox-group.required :checkbox:checked').length > 0
which returns true if at least one element is checked.
Based on that, you can implement your validation check.
Its a simple trick. This is jQuery code that can exploit the html5 validation by changing the required properties if any one is checked. Following is your html code (make sure that you add required for all the elements in the group.)
<input type="checkbox" name="option[]" id="option-1" value="option1" required/> Option 1
<input type="checkbox" name="option[]" id="option-2" value="option2" required/> Option 2
<input type="checkbox" name="option[]" id="option-3" value="option3" required/> Option 3
<input type="checkbox" name="option[]" id="option-4" value="option4" required/> Option 4
<input type="checkbox" name="option[]" id="option-5" value="option5" required/> Option 5
Following is jQuery script, which disables further validation check if any one is selected. Select using name element.
$cbx_group = $("input:checkbox[name='option[]']");
$cbx_group = $("input:checkbox[id^='option-']"); // name is not always helpful ;)
$cbx_group.prop('required', true);
if($cbx_group.is(":checked")){
$cbx_group.prop('required', false);
}
Small gotcha here: Since you are using html5 validation, make sure you execute this before the it gets validated i.e. before form submit.
// but this might not work as expected
$('form').submit(function(){
// code goes here
});
// So, better USE THIS INSTEAD:
$('button[type="submit"]').on('click', function() {
// skipping validation part mentioned above
});
HTML5 does not directly support requiring only one/at least one checkbox be checked in a checkbox group. Here is my solution using Javascript:
HTML
<input class='acb' type='checkbox' name='acheckbox[]' value='1' onclick='deRequire("acb")' required> One
<input class='acb' type='checkbox' name='acheckbox[]' value='2' onclick='deRequire("acb")' required> Two
JAVASCRIPT
function deRequireCb(elClass) {
el = document.getElementsByClassName(elClass);
var atLeastOneChecked = false; //at least one cb is checked
for (i = 0; i < el.length; i++) {
if (el[i].checked === true) {
atLeastOneChecked = true;
}
}
if (atLeastOneChecked === true) {
for (i = 0; i < el.length; i++) {
el[i].required = false;
}
} else {
for (i = 0; i < el.length; i++) {
el[i].required = true;
}
}
}
The javascript will ensure at least one checkbox is checked, then de-require the entire checkbox group. If the one checkbox that is checked becomes un-checked, then it will require all checkboxes, again!
I guess there's no standard HTML5 way to do this, but if you don't mind using a jQuery library, I've been able to achieve a "checkbox group" validation using webshims' "group-required" validation feature:
The docs for group-required say:
If a checkbox has the class 'group-required' at least one of the
checkboxes with the same name inside the form/document has to be
checked.
And here's an example of how you would use it:
<input name="checkbox-group" type="checkbox" class="group-required" id="checkbox-group-id" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
<input name="checkbox-group" type="checkbox" />
I mostly use webshims to polyfill HTML5 features, but it also has some great optional extensions like this one.
It even allows you to write your own custom validity rules. For example, I needed to create a checkbox group that wasn't based on the input's name, so I wrote my own validity rule for that...
we can do this easily with html5 also, just need to add some jquery code
Demo
HTML
<form>
<div class="form-group options">
<input type="checkbox" name="type[]" value="A" required /> A
<input type="checkbox" name="type[]" value="B" required /> B
<input type="checkbox" name="type[]" value="C" required /> C
<input type="submit">
</div>
</form>
Jquery
$(function(){
var requiredCheckboxes = $('.options :checkbox[required]');
requiredCheckboxes.change(function(){
if(requiredCheckboxes.is(':checked')) {
requiredCheckboxes.removeAttr('required');
} else {
requiredCheckboxes.attr('required', 'required');
}
});
});
Inspired by the answers from #thegauraw and #Brian Woodward, here's a bit I pulled together for JQuery users, including a custom validation error message:
$cbx_group = $("input:checkbox[name^='group']");
$cbx_group.on("click", function () {
if ($cbx_group.is(":checked")) {
// checkboxes become unrequired as long as one is checked
$cbx_group.prop("required", false).each(function () {
this.setCustomValidity("");
});
} else {
// require checkboxes and set custom validation error message
$cbx_group.prop("required", true).each(function () {
this.setCustomValidity("Please select at least one checkbox.");
});
}
});
Note that my form has some checkboxes checked by default.
Maybe some of you JavaScript/JQuery wizards could tighten that up even more?
I added an invisible radio to a group of checkboxes.
When at least one option is checked, the radio is also set to check.
When all options are canceled, the radio is also set to cancel.
Therefore, the form uses the radio prompt "Please check at least one option"
You can't use display: none because radio can't be focused.
I make the radio size equal to the entire checkboxes size, so it's more obvious when prompted.
HTML
<form>
<div class="checkboxs-wrapper">
<input id="radio-for-checkboxes" type="radio" name="radio-for-required-checkboxes" required/>
<input type="checkbox" name="option[]" value="option1"/>
<input type="checkbox" name="option[]" value="option2"/>
<input type="checkbox" name="option[]" value="option3"/>
</div>
<input type="submit" value="submit"/>
</form>
Javascript
var inputs = document.querySelectorAll('[name="option[]"]')
var radioForCheckboxes = document.getElementById('radio-for-checkboxes')
function checkCheckboxes () {
var isAtLeastOneServiceSelected = false;
for(var i = inputs.length-1; i >= 0; --i) {
if (inputs[i].checked) isAtLeastOneCheckboxSelected = true;
}
radioForCheckboxes.checked = isAtLeastOneCheckboxSelected
}
for(var i = inputs.length-1; i >= 0; --i) {
inputs[i].addEventListener('change', checkCheckboxes)
}
CSS
.checkboxs-wrapper {
position: relative;
}
.checkboxs-wrapper input[name="radio-for-required-checkboxes"] {
position: absolute;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
-webkit-appearance: none;
pointer-events: none;
border: none;
background: none;
}
https://jsfiddle.net/codus/q6ngpjyc/9/
I had the same problem and I my solution was this:
HTML:
<form id="processForm.php" action="post">
<div class="input check_boxes required wish_payment_type">
<div class="wish_payment_type">
<span class="checkbox payment-radio">
<label for="wish_payment_type_1">
<input class="check_boxes required" id="wish_payment_type_1" name="wish[payment_type][]" type="checkbox" value="1">Foo
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_2">
<input class="check_boxes required" id="wish_payment_type_2" name="wish[payment_type][]" type="checkbox" value="2">Bar
</label>
</span>
<span class="checkbox payment-radio">
<label for="wish_payment_type_3">
<input class="check_boxes required" id="wish_payment_type_3" name="wish[payment_type][]" type="checkbox" value="3">Buzz
</label>
<input id='submit' type="submit" value="Submit">
</div>
</form>
JS:
var verifyPaymentType = function () {
var checkboxes = $('.wish_payment_type .checkbox');
var inputs = checkboxes.find('input');
var first = inputs.first()[0];
inputs.on('change', function () {
this.setCustomValidity('');
});
first.setCustomValidity(checkboxes.find('input:checked').length === 0 ? 'Choose one' : '');
}
$('#submit').click(verifyPaymentType);
https://jsfiddle.net/oywLo5z4/
You don't need jQuery for this. Here's a vanilla JS proof of concept using an event listener on a parent container (checkbox-group-required) of the checkboxes, the checkbox element's .checked property and Array#some.
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEl = formEl.querySelector(".checkbox-group-required");
checkboxGroupEl.addEventListener("click", e => {
statusEl.textContent = validate(checkboxGroupEl) ? "valid" : "invalid";
});
formEl.addEventListener("submit", e => {
e.preventDefault();
if (validate(checkboxGroupEl)) {
statusEl.textContent = "Form submitted!";
// Send data from e.target to your backend
}
else {
statusEl.textContent = "Error: select at least one checkbox";
}
});
<form>
<div class="checkbox-group-required">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
If you have multiple groups to validate, add a loop over each group, optionally adding error messages or CSS to indicate which group fails validation:
const validate = el => {
const checkboxes = el.querySelectorAll('input[type="checkbox"]');
return [...checkboxes].some(e => e.checked);
};
const allValid = els => [...els].every(validate);
const formEl = document.querySelector("form");
const statusEl = formEl.querySelector(".status-message");
const checkboxGroupEls = formEl.querySelectorAll(".checkbox-group-required");
checkboxGroupEls.forEach(el =>
el.addEventListener("click", e => {
statusEl.textContent = allValid(checkboxGroupEls) ? "valid" : "invalid";
})
);
formEl.addEventListener("submit", e => {
e.preventDefault();
if (allValid(checkboxGroupEls)) {
statusEl.textContent = "Form submitted!";
}
else {
statusEl.textContent = "Error: select at least one checkbox from each group";
}
});
<form>
<div class="checkbox-group-required">
<label>
Group 1:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<div class="checkbox-group-required">
<label>
Group 2:
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
<input type="checkbox">
</label>
</div>
<input type="submit" />
<div class="status-message"></div>
</form>
I realize there are a ton of solutions here, but I found none of them hit every requirement I had:
No custom coding required
Code works on page load
No custom classes required (checkboxes or their parent)
I needed several checkbox lists to share the same name for submitting Github issues via their API, and was using the name label[] to assign labels across many form fields (two checkbox lists and a few selects and textboxes) - granted I could have achieved this without them sharing the same name, but I decided to try it, and it worked.
The only requirement for this one is jQuery, which could easily be eliminated if you wanted to rewrite it in vanilla JS. You can combine this with #ewall's great solution to add custom validation error messages.
/* required checkboxes */
jQuery(function ($) {
var $requiredCheckboxes = $("input[type='checkbox'][required]");
/* init all checkbox lists */
$requiredCheckboxes.each(function (i, el) {
//this could easily be changed to suit different parent containers
var $checkboxList = $(this).closest("div, span, p, ul, td");
if (!$checkboxList.hasClass("requiredCheckboxList"))
$checkboxList.addClass("requiredCheckboxList");
});
var $requiredCheckboxLists = $(".requiredCheckboxList");
$requiredCheckboxLists.each(function (i, el) {
var $checkboxList = $(this);
$checkboxList.on("change", "input[type='checkbox']", function (e) {
updateCheckboxesRequired($(this).parents(".requiredCheckboxList"));
});
updateCheckboxesRequired($checkboxList);
});
function updateCheckboxesRequired($checkboxList) {
var $chk = $checkboxList.find("input[type='checkbox']").eq(0),
cblName = $chk.attr("name"),
cblNameAttr = "[name='" + cblName + "']",
$checkboxes = $checkboxList.find("input[type='checkbox']" + cblNameAttr);
if ($checkboxList.find(cblNameAttr + ":checked").length > 0) {
$checkboxes.prop("required", false);
} else {
$checkboxes.prop("required", true);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="post" action="post.php">
<div>
Type of report:
</div>
<div>
<input type="checkbox" id="chkTypeOfReportError" name="label[]" value="Error" required>
<label for="chkTypeOfReportError">Error</label>
<input type="checkbox" id="chkTypeOfReportQuestion" name="label[]" value="Question" required>
<label for="chkTypeOfReportQuestion">Question</label>
<input type="checkbox" id="chkTypeOfReportFeatureRequest" name="label[]" value="Feature Request" required>
<label for="chkTypeOfReportFeatureRequest">Feature Request</label>
</div>
<div>
Priority
</div>
<div>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: High" required>
<label for="chkPriorityHigh">High</label>
<input type="checkbox" id="chkTypeOfContributionBlog" name="label[]" value="Priority: Medium" required>
<label for="chkPriorityMedium">Medium</label>
<input type="checkbox" id="chkTypeOfContributionLow" name="label[]" value="Priority: Low" required>
<label for="chkPriorityMedium">Low</label>
</div>
<div>
<input type="submit" />
</div>
</form>
Really simple way to verify if at least one checkbox is checked:
function isAtLeastOneChecked(name) {
let checkboxes = Array.from(document.getElementsByName(name));
return checkboxes.some(e => e.checked);
}
Then you can implement whatever logic you want to display an error.
Here is another simple trick using Jquery!!
HTML
<form id="hobbieform">
<div>
<input type="checkbox" name="hobbies[]">Coding
<input type="checkbox" name="hobbies[]">Gaming
<input type="checkbox" name="hobbies[]">Driving
</div>
</form>
JQuery
$('#hobbieform').on("submit", function (e) {
var arr = $(this).serialize().toString();
if(arr.indexOf("hobbies") < 0){
e.preventDefault();
alert("You must select at least one hobbie");
}
});
That's all.. this works because if none of the checkbox is selected, nothing as regards the checkbox group(including its name) is posted to the server
Pure JS solution:
const group = document.querySelectorAll('[name="myCheckboxGroup"]');
function requireLeastOneChecked() {
var atLeastOneChecked = false;
for (i = 0; i < group.length; i++)
if (group[i].checked)
atLeastOneChecked = true;
if (atLeastOneChecked)
for (i = 0; i < group.length; i++)
group[i].required = false;
else
for (i = 0; i < group.length; i++)
group[i].required = true;
}
requireLeastOneChecked(); // onload
group.forEach(function ($el) {
$el.addEventListener('click', function () { requireLeastOneChecked(); })
});
Hi just use a text box additional to group of check box.When clicking on any check box put values in to that text box.Make that that text box required and readonly.
A general Solution without change the submit event or knowing the name of the checkboxes
Build a Function, which marks the Checkbox as HTML5-Invalid
Extend Change-Event and check validity on the start
jQuery.fn.getSiblingsCheckboxes = function () {
let $this = $(this);
let $parent = $this.closest('form, .your-checkbox-listwrapper');
return $parent.find('input[type="checkbox"][name="' + $this.attr('name')+'"]').filter('*[required], *[data-required]');
}
jQuery.fn.checkRequiredInputs = function() {
return this.each(function() {
let $this = $(this);
let $parent = $this.closest('form, .your-checkbox-list-wrapper');
let $allInputs = $this.getSiblingsCheckboxes();
if ($allInputs.filter(':checked').length > 0) {
$allInputs.each(function() {
// this.setCustomValidity(''); // not needed
$(this).removeAttr('required');
$(this).closest('li').css('color', 'green'); // for debugging only
});
} else {
$allInputs.each(function() {
// this.reportValidity(); // not needed
$(this).attr('required', 'required');
$(this).closest('li').css('color', 'red'); // for debugging only
});
}
return true;
});
};
$(document).ready(function() {
$('input[type="checkbox"][required="required"], input[type="checkbox"][required]').not('*[data-required]').not('*[disabled]').each(function() {
let $input = $(this);
let $allInputs = $input.getSiblingsCheckboxes();
$input.attr('data-required', 'required');
$input.removeAttr('required');
$input.on('change', function(event) {
$input.checkRequiredInputs();
});
});
$('input[type="checkbox"][data-required="required"]').checkRequiredInputs();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
</head>
<form>
<ul>
<li><input type="checkbox" id="checkbox1" name="countries" value="Argentina" required="required">Argentina</li>
<li><input type="checkbox" id="checkbox2" name="countries" value="France" required="required">France</li>
<li><input type="checkbox" id="checkbox3" name="countries" value="Germany" required="required">Germany</li>
<li><input type="checkbox" id="checkbox4" name="countries" value="Japan" required="required">Japan</li>
<li><input type="checkbox" id="checkbox5" name="countries" value="Australia" required="required">Australia</li>
</ul>
<input type="submit" value="Submit">
</form>
Try:
self.request.get('sports_played', allow_multiple=True)
or
self.request.POST.getall('sports_played')
More specifically:
When you are reading data from the checkbox array, make sure array has:
len>0
In this case:
len(self.request.get('array', allow_multiple=True)) > 0

Javascript adding values to radio buttons to input price

Im trying to create a javascript block inside of a webpage im working on. I havent done javascript since highschool and it doesnt seem to want to come back to me :(
In this block of code i want to have 4 sets of radio buttons, each time a selection is picked,
a price will be inputed to a variable for each radio group. i.e
var firstPrice = $25
var secondPrice = $56
var thirdPrice = $80
var fourthPrice = $90
then after each radio group has one selection there will be a function attached to the submit button that adds up each price to display the final amount inside of a hidden field
var totalPrice = (firstPrice + secondPrice + thirdPrice + fourthPrice)
My question is, how do i attach a number value to a radio button within a group, same name but id is different in each group. Then do i just create a function that adds all the price groups up and then set the submit button to onClick = totalPrice();
Here is an example of one set of radio buttons:
<label>
<input type="radio" name="model" value="radio" id="item_0" />
item 1</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_1" />
item2</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_2" />
item3</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_3" />
Item4</label>
<br />
<label>
<input type="radio" name="model" value="radio" id="item_4" />
item5</label>
</form>
then my script looks something like:
function finalPrice90{
var selectionFirst = document.modelGroup.value;
var selectionSecond = document.secondGroup.value;
var selectionThird = document.thirdGroup.value;
var selectionFourth = document.fourthGroup.Value;
var totalPrice = (selectionFirst + selectionSecond + selectionThird + selectionFourth);
}
Try this fiddle
http://jsfiddle.net/tariqulazam/ZLQXB/
Set the value attribute of your radio inputs to the price each radio button should represent.
When it's time to calculate, simply loop through each group and get the value attribute if the checked radio.
Because the value attribute is a string representation of a number, you'll want to convert it back to a number before doing any math (but that's a simple parseInt or parseFloat).
Here's a working fiddle using pure JavaScript: http://jsfiddle.net/XxZwm/
A library like jQuery or Prototype (or MooTools, script.aculo.us, etc) may make this easier in the long run, depending on how much DOM manipulation code you don't want to re-invent a wheel for.
Your requirements seem pretty simple, here's an example that should answer most questions. There is a single click listener on the form so whenever there is a click on a form control, the price will be updated.
<script type="text/javascript">
//function updatePrice(el) {
function updatePrice(event) {
var el = event.target || event.srcElement;
var form = el.form;
if (!form) return;
var control, controls = form.elements;
var totalPrice = 0;
var radios;
for (var i=0, iLen=controls.length; i<iLen; i++) {
control = controls[i];
if ((control.type == 'radio' || control.type == 'checkbox') && control.checked) {
totalPrice += Number(control.value);
}
// Deal with other types of controls if necessary
}
form.totalPrice.value = '$' + totalPrice;
}
</script>
<form>
<fieldset><legend>Model 1</legend>
<input type="radio" name="model1" value="25">$25<br>
<input type="radio" name="model1" value="35">$35<br>
<input type="radio" name="model1" value="45">$45<br>
<input type="radio" name="model1" value="55">$55<br>
</fieldset>
<fieldset><legend>Model 2</legend>
<input type="radio" name="model2" value="1">$1<br>
<input type="radio" name="model2" value="2">$2<br>
<input type="radio" name="model2" value="3">$3<br>
<input type="radio" name="model2" value="4">$4<br>
<fieldset><legend>Include shipping?</legend>
<span>$5</span><input type="checkbox" value="5" name="shipping"><br>
</fieldset>
<input name="totalPrice" readonly><br>
<input type="reset" value="Clear form">
</form>
You could put a single listener on the form for click events and update the price automatically, in that case you can get rid of the update button.

Categories

Resources