Validate multiple choice radio buttons with Javascript - javascript

I want to prevent the form ( with id="new_question") from being submitted if an answer (radio button) is not checked from that radio group.
<input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">
<input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">
<input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit"></input>
There are ten radio groups (with the same html above) that require one answer checked.
The form id is "new_question"
So need help making a validation that doesn't allow the form to be submitted unless all the answers are checked.
What I have so far:
validateForm = function() {
x = document.forms['new_question']['question[q1correct]'].value;
if (x === null || x === '') {
alert('Name must be filled out');
return false;
}
};
I do need this for the rest of the 10 radio groups but I think once I know how to do it on one, I can implement the code on all the radio groups.

assuming that kind of html:
<form id="foo">
<div class='selectGroup'>
<input class="radioclass" id="q1a" value="a" name="question[q1correct]" type="radio">1</input>
<input class="radioclass" id="q1b" value="b" name="question[q1correct]" type="radio">2</input>
<input class="radioclass" id="q1c" value="c" name="question[q1correct]" type="radio">3</input>
<input class="radioclass" id="q1d" value="d" name="question[q1correct]" type="radio">4</input>
</div>
<div class='selectGroup'>
<input class="radioclass" id="q2a" value="a" name="question[q2correct]" type="radio">1</input>
<input class="radioclass" id="q2b" value="b" name="question[q2correct]" type="radio">2</input>
<input class="radioclass" id="q2c" value="c" name="question[q2correct]" type="radio">3</input>
<input class="radioclass" id="q2d" value="d" name="question[q2correct]" type="radio">4</input>
</div>
<input id="publishbtn" class="greenbtn" type="submit" value="PUBLISH" name="commit">
</input>
</form>
you might use following js
$('#foo').submit(function(e) {
e.preventDefault();
var $form = $(e.currentTarget)
var groupsValidationList = []
selectGroups = $form.children('.selectGroup')
selectGroups.each(function(index, group) {
$group = $(group);
checks = $group.children('.radioclass').map(function(index, radioItem) {
return $(radioItem).is(':checked')
})
isValid = ($.inArray(true, checks) != -1);
groupsValidationList.push(isValid);
})
if(groupsValidationList.every(function(validationResult) { return validationResult; })) {
alert('ok');
} else {
alert('at least one group is not marked');
}
})
https://jsfiddle.net/4qwvgqkz/

Related

Can a radio button in a form be used to select another radio button in the same form?

I have a HTML form that has 2 groups of radio buttons. I need the first group to also change the selection on the second group, i.e.
Group 1 has options A & B, Group 2 has options C & D;
when I select A, I need the form to also select C; when I select B, I need the form to also select D.
I need A & C selected by default when the page loads.
A & C will always be paired; B & D will always be paired.
I know this sounds impractical, but the reason is that this form is sending its responses to another provider's form where I can't edit the fields. They have effectively got a duplicate question in their form (same question just slightly different wording), and I don't want my users to have to answer the same question twice, so I would hope to hide the buttons for C & D from view.
The "name" on the each group is different, and the "value" & "id" for each radio button is unique.
Can this be done? JQuery & JS solutions are welcome.
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<label class="label-text" for="buyer">Buyer</label>
<input type="radio" name="agent" id="buyer" value="false">
<label class="label-text" for="agent">Agent</label>
<input type="radio" name="agent" id="agent" value="true">
Simply set the checked property of the corresponding button.
document.getElementById("buyer").checked = true;
document.getElementById("buyer-select").addEventListener("click", function() {
document.getElementById("buyer").checked = true;
});
document.getElementById("agent-select").addEventListener("click", function() {
document.getElementById("agent").checked = true;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<br>
<label class="label-text" for="buyer">Buyer</label>
<input type="radio" name="agent" id="buyer" value="false">
<label class="label-text" for="agent">Agent</label>
<input type="radio" name="agent" id="agent" value="true">
You can also replace the second set of radio buttons with a single hidden input. Put the values that would have been sent by the radio button into the value of the hidden input.
document.getElementById("buyer-select").addEventListener("click", function() {
document.getElementById("buyer-agent").value = "false";
});
document.getElementById("agent-select").addEventListener("click", function() {
document.getElementById("buyer-agent").value = "true";
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label for="buyer-select">
<div class="user-select-label">Buyer</div>
</label>
<input type="radio" name="answers[1234][answers]" id="buyer-select" class="buyer-select" value="buyer" checked>
<label for="agent-select">
<div class="user-select-label">Agent</div>
</label>
<input type="radio" name="answers[1234][answers]" id="agent-select" class="agent-select" value="broker">
<input type="hidden" name="agent" id="buyer-agent" value="false">
Is this what you wanted:
If yes, try this code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script type="text/javascript">
document.addEventListener('DOMContentLoaded', function() {
$('input[type=radio][name="pet"]').change(function() {
var $radiobutton = $("input[value='"+$(this).val()+"']");
$radiobutton.prop("checked", true);
});
$('input[type=radio][name="pet2"]').change(function() {
var $radiobutton = $("input[value='"+$(this).val()+"']");
$radiobutton.prop("checked", true);
});
}, false);
</script>
</head>
<h2>Select a Pet</h2>
<div>
<input name="pet" type="radio" value="dog" /><span>Dog</span>
<input name="pet" type="radio" value="cat" /><span>Cat</span>
<input name="pet" type="radio" value="fish" /><span>Fish</span>
</div>
<div>
<input name="pet2" type="radio" value="dog" /><span>Dog</span>
<input name="pet2" type="radio" value="cat" /><span>Cat</span>
<input name="pet2" type="radio" value="fish" /><span>Fish</span>
</div>

How to toggle HTML radio button with jQuery?

I have a radio button that is checked by default. What I am trying to accomplish is just to toggle it on/off with a click and simple logic but I do not understand what I'm doing wrong.
Here is my HTML:
<input type="radio" id="member" name="member" value="member" checked>
<label for="member" >Member Reported</label>
And here is my jQuery:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
}
})
This works great, but I noticed that it's not changing the DOM once clicked, and furthermore, when I try to add the prop to true (like below), it's not checking back on the GUI.
Here's the DOM:
$('#member').click((e) => {
console.log('click')
if($('#member').is(':checked')) {
$('#member').prop('checked',false)
} else if (!$('#member').is(':checked')) {
$('#member').prop('checked',true)
}
})
How about this? Is this what you are willing?
$('#member + label').click((e) => {
console.log($('#member')[0].checked);
if($('#member')[0].checked) {
$('#member')[0].checked = false;
} else{
$('#member')[0].checked = true;
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" name="member" value="member" checked >
<label for="" >Member Reported</label>
As long checked exist in element, it will stay checked. You will have to remove it via jquery to make it work.
You can check functioning here.
<input type="radio" checked>
<br>
<input type="radio" checked="true">
<br>
<input type="radio" checked="false">
<br>
<input type="radio">
I think that's the way it should be.
$('.radios').click((e) => {
$('.radios').each(function (i) {
$(this).removeAttr('checked')
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" id="member" class="radios" name="member" value="member" >
<label for="member" >Member Reported</label><br/>
<input type="radio" id="member2" class="radios" name="member" value="member" >
<label for="member2" >Member Reported2</label><br/>
<input type="radio" id="member3" class="radios" name="member" value="member" checked>
<label for="member3" >Member Reported3</label><br/>

Validation of at least one set of radio group

I have two groups of radio buttons
<input type="radio" name="rb1" value="a">
<input type="radio" name="rb1" value="b">
<input type="radio" name="rb1" value="c">
<input type="radio" name="rb2" value="e">
<input type="radio" name="rb2" value="f">
<input type="radio" name="rb2" value="g">
Now, user:
1. has to select at least one value from either radio groups
2. can select one value from each of the two groups
I need to use javascript for validation. I can validate one or both groups, but how do I check for both?
You want to do something like this...
$('#btnValidate').click(function() {
var v1 = $('input:radio[name="rb1"]:checked').val();
var v2 = $('input:radio[name="rb2"]:checked').val();
if (!v1 && !v2 ) {
alert('not valid');
} else {
alert('valid');
}
});
working jsfiddle here...
http://jsfiddle.net/CEJLt/

Accessing the radio button value

Html Code: -
<input type="radio" name="radio" id="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate()"> For Users</input>
</p>
And JavaScript Code : -
function validate()
{
var btn_value=document.getElementById("radio").value;
if(btn_value==true)
{
alert(btn_value);
}
}
Now, whenever I am trying to print the value of radio button. It is always printing value as 1.
So, Now I don't understand what exactly am I missing here...
Thanx in advance for your help.
Elements ID should be unique. I modified your HTML and JS part and check below
Try this
HTML
<p>
<input type="radio" name="radio" id="radio1" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio2" value="2" onclick="validate(this)"> For Users</input>
</p>
JavaScrpit
function validate(obj)
{
var btn_value=obj.value;
if(btn_value==true)
{
alert(btn_value);
}
}
first of all never use a DOMID twice in your html!
remove them.... only use dublicated names!
<input type="radio" name="radio" value="1" onclick="validate()"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" value="2" onclick="validate()"> For Users</input>
</p>
with the js check every element with the name attribute!
function validate() {
var elements = document.getElementsByName("radio");
for(var n = 0; n < elements.length; n++) {
if(elements[n].checked === true) {
alert(elements[n].value);
}
}
}
if you use your validate method ONLY in the onclick you can pass the domelement in the validate methode like this:
<input type="radio" name="radio" value="1" onclick="validate(this)"> For Yourself</input> </p>
and your js:
function validate(domElement) {
if(domElement.checked === true) {
alert(elements[n].value);
}
}
try this
<input type="radio" name="radio" id="radio" value="1" onclick="validate(this)"> For Yourself</input> </p></br>
<p>
<input type="radio" name="radio" id="radio" value="2" onclick="validate(this)"> For Users</input>
</p>​
function validate(ele)
{
alert(ele.value);
}​
IDs MUST be unique, it's a mistake to give it the same id.
You can give the IDs a running number (- radio1,radio2 etc) and loop through them to check which one was selected.

How can I make a group of checkboxes mutually exclusive?

I have to make mutually exculsive checkboxes. I have come across numerous examples that do it giving example of one checkbox group.
One example is at http://blog.schuager.com/2008/09/mutually-exclusive-checkboxes-with.html.
In my case, I have many checkbox groups on the same page, so I want it to work like this example.
An asp.net codebehind example is here, but I want to do it in client side code.
How can I do this in JavaScript?
i have decided to use the ajax mutually exclusive checkbox extender.
The solutions given so far are basically based on radio buttons.
This link really helped me..http://www.asp.net/ajax/videos/how-do-i-use-the-aspnet-ajax-mutuallyexclusive-checkbox-extender
Using Mutual Checkboxes when there is Radio button is a bad idea but still you can do this as follows
HTML
<div>
Red: <input id="chkRed" name="chkRed" type="checkbox" value="red" class="checkbox">
Blue: <input id="chkBlue" name="chkBlue" type="checkbox" value="blue" class="checkbox">
Green: <input id="chkGreen" name="chkGreen" type="checkbox" value="green" class="checkbox">
</div>
<div>
Mango: <input id="chkRed" name="chkMango" type="checkbox" value="Mango" class="checkbox">
Orange: <input id="chkBlue" name="chkOrange" type="checkbox" value="Orange" class="checkbox">
Banana: <input id="chkGreen" name="chkBanana" type="checkbox" value="Banana" class="checkbox">
</div>
Jquery
$('div .checkbox').click(function () {
checkedState = $(this).attr('checked');
$(this).parent('div').children('.checkbox:checked').each(function () {
$(this).attr('checked', false);
});
$(this).attr('checked', checkedState);
});
And here is fiddle
Like I said in my comment, you should really use <radio> elements for this. Give them the same name and they work almost the same way:
<label><input type="radio" name="option" value="Option 1">Option 1</label>
<label><input type="radio" name="option" value="Option 2">Option 2</label>
The only significant difference is that, once one of them is selected, at least one of them has to be on (ie, you can't uncheck them again).
If you really feel the need to do it with check boxes, remind yourself that users with JavaScript disabled will be able to select all the options if they like. If you still feel the need to do it, then you'll need to give each checkbox group a unique class name. Then, handle the change event of each checkbox element and uncheck all the other elements matching the same class name as the clicked element.
I hope this one will work
HTML
A <input type="checkbox" class="alpha" value="A" /> |
B <input type="checkbox" class="alpha" value="B" /> |
C <input type="checkbox" class="alpha" value="C" />
<br />
1 <input type="checkbox" class="num" value="1" /> |
2 <input type="checkbox" class="num" value="2" /> |
3 <input type="checkbox" class="num" value="3" />
JavaScript
// include jQuery library
var enforeMutualExcludedCheckBox = function(group){
return function() {
var isChecked= $(this).prop("checked");
$(group).prop("checked", false);
$(this).prop("checked", isChecked);
}
};
$(".alpha").click(enforeMutualExcludedCheckBox(".alpha"));
$(".num").click(enforeMutualExcludedCheckBox(".num"));
well, radio button should be the one to be used in mutually excluded options, though I've encountered a scenario where the client preferred to have zero to one selected item, and the javaScript'ed checkbox works well.
Update
Looking at my answer, I realized it's redundant to refer to the css class twice. I updated my code to convert it into a jquery plugin, and created two solutions, depending on ones preference
Get all checkboxes whose check is mutually excluded
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this; // refers to selected checkboxes
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// more elegant, just invoke the plugin
$("[name=alpha]").mutuallyExcludedCheckBoxes();
$("[name=num]").mutuallyExcludedCheckBoxes();
HTML
A <input type="checkbox" name="alpha" value="A" /> |
B <input type="checkbox" name="alpha" value="B" /> |
C <input type="checkbox" name="alpha" value="C" />
<br />
1 <input type="checkbox" name="num" value="1" /> |
2 <input type="checkbox" name="num" value="2" /> |
3 <input type="checkbox" name="num" value="3" />
sample code
Group all mutually excluded checkboxes in a containing element
JavaScript
$.fn.mutuallyExcludedCheckBoxes = function(){
var $checkboxes = this.find("input[type=checkbox]");
$checkboxes.click(function() {
var $this = $(this),
isChecked = $this.prop("checked");
$checkboxes.prop("checked", false);
$this.prop("checked", isChecked);
});
};
// select the containing element, then trigger the plugin
// to set all checkboxes in the containing element mutually
// excluded
$(".alpha").mutuallyExcludedCheckBoxes();
$(".num").mutuallyExcludedCheckBoxes();
HTML
<div class="alpha">
A <input type="checkbox" value="A" /> |
B <input type="checkbox" value="B" /> |
C <input type="checkbox" value="C" />
</div>
<div class="num">
1 <input type="checkbox" value="1" /> |
2 <input type="checkbox" value="2" /> |
3 <input type="checkbox" value="3" />
</div>
sample code
Enjoy :-)
Try this:
HTML
<div>
Car: <input id="chkVehicleCar" name="chkVehicle" type="checkbox" value="Car" class="radiocheckbox">
Moto: <input id="chkVehicleMoto" name="chkVehicle" type="checkbox" value="Moto" class="radiocheckbox">
Byke: <input id="chkVehicleByke" name="chkVehicle" type="checkbox" value="Byke" class="radiocheckbox">
Feet: <input id="chkVehicleFeet" name="chkVehicle" type="checkbox" value="Feet">
</div>
<span>
Red: <input id="chkColorRed" name="chkColor" type="checkbox" value="Red" class="radiocheckbox">
Blue: <input id="chkColorBlue" name="chkColor" type="checkbox" value="Blue" class="radiocheckbox">
Green: <input id="chkColorGreen" name="chkColor" type="checkbox" value="Green" class="radiocheckbox">
Mango: <input id="chkFruitMango" name="chkFruit" type="checkbox" value="Mango" class="radiocheckbox">
Orange: <input id="chkFruitOrange" name="chkFruit" type="checkbox" value="Orange" class="radiocheckbox">
Banana: <input id="chkFruitBanana" name="chkFruit" type="checkbox" value="Banana" class="radiocheckbox">
</span>
​JavaScript/jQuery
$(':checkbox.radiocheckbox').click(function() {
this.checked
&& $(this).siblings('input[name="' + this.name + '"]:checked.' + this.className)
.prop('checked', false);
});​
Mutually exclusive checkboxes are grouped by container+name+classname.
You can use different groups in same container and also mix exclusive with non-exclusive checkbox with same name.
JavaScript code is highly optimized. You can see a working example.
No matter where the check box is located on your page, you just need to specify the group and here you go!
<input type='checkbox' data-group='orderState'> pending
<input type='checkbox' data-group='orderState'> solved
<input type='checkbox' data-group='orderState'> timed out
<input type='checkbox' data-group='sex'> male
<input type='checkbox' data-group='sex'> female
<input type='checkbox'> Isolated
<script>
$(document).ready(function () {
$('input[type=checkbox]').click(function () {
var state = $(this)[0].checked,
g = $(this).data('group');
$(this).siblings()
.each(function () {
$(this)[0].checked = g==$(this).data('group')&&state ? false : $(this)[0].checked;
});
});
})</script>
I guess this is what you want.
Consider the HTML below:
<form action="">
My favourite colors are:<br />
<br />
<input type="checkbox" value="red" name="color" /> Red<br />
<input type="checkbox" value="yellow" name="color" /> Yellow<br />
<input type="checkbox" value="blue" name="color" /> Blue<br />
<input type="checkbox" value="orange" name="color1" /> Orange<br />
<input type="checkbox" value="green" name="color1" /> Green<br />
<input type="checkbox" value="purple" name="color1" /> Purple
</form>
Note that there's two names for color groups: red, yellow, blue and orage, green, purple
And this JavaScript noted below will work generically to all checkbox on the page.
jQuery("input[type=checkbox]").unbind("click");
jQuery("input[type=checkbox]").each(function(index, value) {
var checkbox = jQuery(value);
checkbox.bind("click", function () {
var check = checkbox.attr("checked");
jQuery("input[name=" + checkbox.attr('name') + "]").prop("checked", false);
checkbox.attr("checked", check);
});
});
Take a look at this LIVE example

Categories

Resources