Checkbox: jQuery required function - javascript

This is the code I'm using to display questions where users are required to select one or more checkboxes as answers:
$QA = '<label for="q'.$QID.'-'.$Value.'"><input type="checkbox" name="q'.$QID.'[]" id="q'.$QID.'-'.$Value.'" value="'.$Value.'"> '.$QA.'</label>';
And here's a typical display:
<li id="q8">
<div class="Question">Which ones are countries?</div>
<div class="Answer">
<label for="q6-A"><input type="checkbox" name="q6[]" id="q6-A" value="A"> Texas</label>
<label for="q6-B"><input type="checkbox" name="q6[]" id="q6-B" value="B"> Japan</label>
<label for="q6-C"><input type="checkbox" name="q6[]" id="q6-C" value="C"> Spain</label>
</div>
</li>
I want to modify the code so that the form won't submit unless a user selects at least one checkbox. Every script I've tried requires them to choose EVERY checkbox, but I just want to make sure they attempt to answer the question by choosing ANY ONE checkbox.
Someone suggested the following script:
$('input[type=checkbox][name=gender]')[0].attr('required', 'required');;
So I replaced "name=gender" with "name=q6[]", but that doesn't work. I'm guessing the brackets after q6 might be a problem, but if I remove the brackets from the code that drives the form - name="q'.$QID.'[]" - then the test is scored incorrectly on the results page.
Another problem is that this script requires a specific name, when similar multiple-choice checkbox questions on various tests can have various names.
Is there some way to modify this script so that it targets ALL questions that have checkboxes, requiring users to select at least one checkbox?

Try this out...
if(($('input[name="q6[]"]:checked') != undefined) && ($('input[name="q6[]"]:checked') != null)) {
console.log("true");
} else {
console.log("false");
}

Related

Contact Form 7 Required Checkbox Group Validation Issue

I am using a Contact Form 7 form in Wordpress. I have a group of checkboxes, of which I would like to make sure at least one is checked before the form is submitted. Should be simple enough... With the built in validation, because I am not using the CF7 short code, but html input markup, even if the fields are set to required, the form submits. I cannot use the short code because my input field names contain [] brackets. So, I installed Jquery validation plugin for CF7, which works fine to disallow the form to be submitted if none of the boxes are checked, but if you check, say, the first 3 boxes, only the values of the second and third boxes are sent through the form. I have looked around at several custom validation code snippets which look like they would work and I paste them into the same area as I have other similar snippets doing other things and they don't make a difference because the built in CF7 validation doesn't stop the form from submitting when the required fields of my html input fields aren't checked. Any suggestions? I am not a coder (doing my best though) so please feel free to answer like I am a child lol. Here is my html:
<p>
<label>Which Are You Most Interested In?</label>
</br>
<label for="cb1">
<input id="cb1" name="mc4wp-INTERESTS[de9f89w3vq][]"
type="checkbox" value="bf2fd8233f" required> <span>Interest 1</span>
</label>
</br>
<label for="cb2">
<input id="cb2" name="mc4wp-INTERESTS[de9f89w3vq][]"
type="checkbox" value="c1b1b74e7c" required> <span>Interest 2</span>
</label>
</br>
<label for="cb3">
<input id="cb3" name="mc4wp-INTERESTS[de9f89w3vq][]"
type="checkbox" value="a4c5eb6f36" required> <span>Interest 3</span>
</label>
</br>
<label for="cb4">
<input id="cb4" name="mc4wp-INTERESTS[de9f89w3vq][]"
type="checkbox" value="587de639d6" required> <span>Interest 4</span>
</label>
</p>
--
I figured the best way for me to go about this is to just disable the submit button until the group of checkboxes has had at least one value checked (and another set of radio buttons having had one checked) and found this code:
(function($) {
function buttonState(){
$("input").each(function(){
$('#send-info').attr('disabled', 'disabled');
if($(this).val() == "" ) return false;
$('#send-info').attr('disabled', '');
})
}
$(function(){
$('#send-info').attr('disabled', 'disabled');
$('input').change(buttonState);
})
})(jQuery);
... Which works really nicely to disable the submit button, however it seems like since I have hidden fields it does not re-enable the submit button. Also not sure if it cares about required fields only. Wondering how to modify it so that it only cares about required fields and ignores hidden fields. I tried several other snippet solutions and for some reason they were not disabling the submit button. I have the script installed at the bottom of the page via Scripts and Styles Wordpress plugin.

Make checkboxes required

I already looked to similar questions but I still can't figure out how to fix it. On my webpage, I have some radio checkboxes which I would like to be required before going to the next question.
I have the following partial code:
<p>
Select the option that fits most to you<br><br>
<label>
<input type="radio" name="typesport" value="teamsport" >
I prefer a teamsport</label><br>
<label>
<input type="radio" name="typesport" value="individual">
I prefer an individual sport</label><br>
</p>
Next question
Can someone help me with getting a javascript code, that actually works for all radio-boxes, where you could only go to the next question when 1 radio-box is selected?
Cheers,
Max
Edit: What I've tried so far is the following:
I added "required" to the label, so it looked like this:
<label><input type="radio" name="typesport" value="teamsport" required> I prefer a teamsport</label><br>
I also added the ID to the button:
Next question
Furthermore, I used this JS script:
$(document).ready(function () {
$('#checkBtn').click(function() {
checked = $("input[type=radio]:checked").length;
if(!checked) {
alert("You must check at least one radio.");
return false;
}
});
});
However, this works fine for only one question. When I add this to all the other questions, I still can go to the following question when I click on the button Next question, and that is not what I want.
Radio boxes are fairly simple in nature in that you should always have at least one option in a radio-group checked by default. Preferably a N/A or 'Please Select' option.
In which case you would want to validate against the 'Please Select' option instead:
//when user clicks <a> element
$(".next-button").click(function() {
//group on radio button name and test if checked
if ($("input[name='typesport']:checked").val() == 'select') {
alert('Nothing is checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Select the option that fits most to you<br><br>
<label><input type="radio" name="typesport" value="select" checked="true" > Please Select </label><br>
<label><input type="radio" name="typesport" value="teamsport" > I prefer a teamsport</label><br>
<label><input type="radio" name="typesport" value="individual"> I prefer an individual sport</label><br>
</p>
Next question
However
If you really want to validate that an option has been checked:
This should work:
//when user clicks <a> element
$(".next-button").click(function()
{
//group on radio button name and test if checked
if (!$("input[name='typesport']:checked").val()) {
alert('Nothing is checked!');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
Select the option that fits most to you<br><br>
<label><input type="radio" name="typesport" value="teamsport" > I prefer a teamsport</label><br>
<label><input type="radio" name="typesport" value="individual"> I prefer an individual sport</label><br>
</p>
Next question
HTML5 supports the required attribute for radio buttons. I did some searching and HTML5: How to use the "required" attribute with a "radio" input field has more detailed information about this attribute.
You can set a radio button checked by default by using the checked attribute.
To check if it's checked or not, use this code :
if ($('input[name=typesport]').attr('value') != undefined) {
//execute code when it is checked
} else {
//execute code when it's not checked
}

How to get the value of an input radio button and do something based on answer?

I'm essentially making a 10 question quiz. I know there's a ton of ways out there to do this and lots of answers on how to get the value of the input radio button, but I just can't quite figure it out! I'm using Foundation 5's Abide Validation for the "required" attribute and the "on('valid.fndtn.abide')", which is just making sure an answer is selected right now.
HTML
<h2>Choose one answer:</h2>
<div class="radio">
<div class="input-radio"><input type="radio" name="question_10" value="Wrong" id="option_37" required><label for="option_37">Answer 37</label></div>
<div class="input-radio"><input type="radio" name="question_10" value="Wrong" id="option_38" required><label for="option_38">Answer 38</label></div>
<div class="input-radio"><input type="radio" name="question_10" value="Wrong" id="option_39" required><label for="option_39">Answer 39</label></div>
<div class="input-radio"><input type="radio" name="question_10" value="Correct" id="option_40" required><label for="option_40">Answer 40</label></div>
</div>
Javascript (sans other stuff) that I have now. Right now this is returning "No" even if I select the right answer. If I make all the answers "Correct", it will return "Yes".
$(document).ready(function(){
$('.form-prepare').on('valid.fndtn.abide', function(e) {
var answer10 = $("input[name='question_10']").val();
if (answer10 === "Correct") { alert("Yes!"); }
else { alert("No!");
e.preventDefault();
});
});
EDIT: Removed second part of the question, as I see it could be it's own question in itself. As per the answer, I was missing the :checked part of my input variable. Thanks!
jQuery's .val() method will only return the value of the first element when a collection is returned by the selector, so you are always retrieving the value of the first input with name equal to question_10.
To properly retrieve the value you are after you need to limit your selector to only return the checked element, like this:
$("input[name='question_10']:checked").val();

Clear Checkbox when Radio Button selection is Changed

I am using a form builder with field IDs in Wordpress. I need to uncheck a specific checkbox if a specific radio button selection is changed. The radio button's field ID is 180. The checkbox's field ID is 640. Here's what I tried first:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input[name="item_meta[180]"]').change(function(){
$('input[name="item_meta[640]"]').val('');
})
})
</script>
Note that this script was originally written to change the value of a dropdown, not a menu. The only change I made to the code was changing "select" to "input" on line 3.
I've also tried changing
.val('');
to
.attr('checked', false);
and also to
.removeAttr('checked');
None of these work. The checkbox remains checked when the radio button is changed. Does anyone have any ideas? Thanks in advance!
UPDATE: Here are the two relevant form fields in HTML:
<div id="frm_field_180_container" class="frm_form_field form-field frm_required_field frm_top_container">
<label class="frm_primary_label">Pricing Categories
<span class="frm_required">*</span>
</label>
<div class="frm_description">Select your meta-category then locate your entry fee in the subsequent dropdown.</div>
<div class="frm_radio"><input type="radio" name="item_meta[180]" id="field_180-0" value="Independent Film & Videos" class="required" onclick="frmCheckDependent(this.value,'180')"/><label for="field_180-0">Independent Film & Videos</label></div>
<div class="frm_radio"><input type="radio" name="item_meta[180]" id="field_180-1" value="Film / Video for TV & Cable Production" class="required" onclick="frmCheckDependent(this.value,'180')"/><label for="field_180-1">Film / Video for TV & Cable Production</label></div>
<div class="frm_radio"><input type="radio" name="item_meta[180]" id="field_180-2" value="TV Ads, PSAs, Screenplays, New Media, Websites, etc." class="required" onclick="frmCheckDependent(this.value,'180')"/><label for="field_180-2">TV Ads, PSAs, Screenplays, New Media, Websites, etc.</label></div>
<div class="frm_radio"><input type="radio" name="item_meta[180]" id="field_180-3" value="Student Entry of Any Category (with 2 Additional Categories Free) - $45" class="required" onclick="frmCheckDependent(this.value,'180')"/><label for="field_180-3">Student Entry of Any Category (with 2 Additional Categories Free) - $45</label></div>
</div>
and
<div id="frm_field_640_container" class="frm_form_field form-field frm_top_container frm_last_third">
<label class="frm_primary_label">Apply Early-Bird Discount
<span class="frm_required"></span>
</label>
<div class="frm_opt_container"><div class="frm_checkbox" id="frm_checkbox_640-0"><input type="checkbox" name="item_meta[640][]" id="field_640-0" value="5" /><label for="field_640-0">1-3 Categories: $5</label></div>
</div>
The following approach appears to work:
$('input[name="item_meta\\[180\\]"]').change(function(){
$('input[name="item_meta\\[640\\]\\[\\]"]').prop('checked',false);
});
JS Fiddle demo.
Note that I removed the onclick (since they weren't defined, their absence generated errors, and if you're using jQuery why are you even using in-line event-handlers?). Also, the escaping of the square-brackets (using the \\ characters).
References:
prop().
You've got a mismatch for the name of the checkbox, between your HTML and your JQuery . . .
HTML
<input type="checkbox" name="item_meta[640][]" id="field_640-0" value="5" />
Here, the name attribute is item_meta[640][].
JS
$('input[name="item_meta[640]"]').val('');
Here, the name attribute is item_meta[640].
Because of that, the selector is not matching the checkbox. If you update you JQuery selector to $('input[name="item_meta[640][]"]'), it should work fine.
As noted by Dave Thomas, you are better going with .prop('checked', false); to uncheck the box.

Rails: two radio selects on same source list

Wondering how to approach this... Best to look at the picture to visualize the, hopeful, UI for a form for choosing options in a list. Users need to be able to make a first choice and a second choice for each option. One and only one can be selected in each column, and for that matter, each row.
At first I thought, naturally, 2 radio button groups might work...but not sure how? Perhaps hidden radio_buttons whose values are manipulated via Javascript/JQuery in a click event on each div? Event should also check/handle "collisions" when user tries to select same option for both choices.
Or, would this perhaps be better with two hidden collection_selects...or even simpler, just two hidden text_fields...which javascript can populate with the ID of the selected option?
Or maybe I'm overlooking something more obvious.
I'm new(ish) to javascripting with Rails so looking for advice/validation.
Thanks.
I think something like this is what your looking for:
HTML:
<form>
<p class="exclusiveSelection">
Selection One
<input type="radio" name="firstColumn"/>
<input type="radio" name="secondColumn"/>
</p>
<p class="exclusiveSelection">
Selection Two
<input type="radio" name="firstColumn"/>
<input type="radio" name="secondColumn"/>
</p>
<p class="exclusiveSelection">
Selection Three
<input type="radio" name="firstColumn"/>
<input type="radio" name="secondColumn"/>
</p>
<input type="button" id="submitForm" value="Submit">
</form>
JavaScript:
$(function() {
$(".exclusiveSelection input[type='radio']").click(function() {
$exclusiveSelection = $(this).parent();
$('input[type='radio']', $exclusiveSelection).attr('checked', false);
$(this).attr('checked', true);
});
});
It ensures that the values are unique across column and row and works with jQuery 1.2.6 - 1.7.1. There is also a JSFiddle example.
If you need help adapting this for Rails let me know, however it should be straight forward.

Categories

Resources