How to be simpler in this JavaScript? - javascript

I am trying to make a Js to search & filter items in JSON
so I use many radio in the "form" , the result will be [X,X,X,X,X,X]
I will set 50tags x 3(choose), I can feel my function will be large.
What ways can I change my function to be simpler?
function myFunction() {
var elements1 = document.getElementsByName("chair"),
elements2 = document.getElementsByName("car"),
elements3 = document.getElementsByName("house"),
elements4 = document.getElementsByName("tree"),
elements5 = document.getElementsByName("flower"),
elements6 = document.getElementsByName("grass");
var i;
for (var a = "", i = elements1.length; i--;) {
if (elements1[i].checked) {
var a = elements1[i].value;
break;
}
};
for (var b = "", i = elements2.length; i--;) {
if (elements2[i].checked) {
var b = elements2[i].value;
break;
}
};
for (var c = "", i = elements3.length; i--;) {
if (elements3[i].checked) {
var c = elements3[i].value;
break;
}
};
for (var d = "", i = elements4.length; i--;) {
if (elements4[i].checked) {
var d = elements4[i].value;
break;
}
};
for (var e = "", i = elements5.length; i--;) {
if (elements5[i].checked) {
var e = elements5[i].value;
break;
}
};
for (var f = "", i = elements6.length; i--;) {
if (elements6[i].checked) {
var f = elements6[i].value;
break;
}
};
var o2 = document.getElementById("output2");
o2.value = "[" + a + "," + b + "," + c + "," + d + "," + e + "," + f + "]";
o2.innerHTML = o2.value;
}
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter" onclick="myFunction()" /> </div>
</form>
<div id="output2"></div>

Give the form an id, and you can refer to it as an object.
function myFunction() {
var form = document.getElementById("myForm");
var parts = [
form.chair.value,
form.car.value,
form.house.value,
form.tree.value,
form.flower.value,
form.grass.value
];
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}
And this is an even simpler solution using a FormData object. It supports an arbitrary number of named form fields without having to actually name them in the function:
function myFunction() {
var myForm = document.getElementById('myForm');
var formData = new FormData(myForm);
var parts = Array.from(formData.values());
var o2 = document.getElementById("output2");
o2.innerHTML = '[' + parts.join(',') + ']';
}

Use document.querySelector() to directly select the value of the checked radio button based on element names.
function myFunction() {
var chair = document.querySelector('input[name="chair"]:checked').value;
var car = document.querySelector('input[name="car"]:checked').value;
var house = document.querySelector('input[name="house"]:checked').value;
var tree = document.querySelector('input[name="tree"]:checked').value;
var flower = document.querySelector('input[name="flower"]:checked').value;
var grass = document.querySelector('input[name="grass"]:checked').value;
var o2 = document.getElementById("output2");
o2.value = "[" + chair + "," + car + "," + house + "," + tree + "," + flower + "," + grass + "]";
o2.innerHTML = o2.value;
}

Use arrays!
function myFunction() {
var elem_ids = [ "chair", "car", "house", "tree", "flower", "grass"];
var elems = elem_ids.map(id => document.getElementById(id));
var elems_check_values = elems.map(el => {
// el is kind of an array so
for(var i = 0; i < el.length; ++i)
if(el[i].checked)
return el[i].value;
return undefined;
}).filter(value => value == undefined) // to filter undefined values;
var output = "[" + elems_check_values.join(",") + "]";
var o2 = document.getElementById("output2");
o2.innerHTML = output
}

Your issue can be generalized to: how can I aggregate values for all fields in a given form?
The solution is a function that can be merely as long as 5 lines, and work for any amount of inputs with any type. The DOM model for <form> elements provides named keys (eg, myform.inputName) which each have a value property. For radio buttons, eg myform.tree.value will automatically provide the value of the selected radio button.
With this knowledge, you can create a function with a simple signature that takes a form HTMLElement, and an array of field names for the values that you need, like below: (hit the search button for results, and feel free to change the radio buttons).
function getFormValues(form, fields) {
var result = [];
for (var i = 0; i < fields.length; i++) {
result.push(form[fields[i]].value);
}
return result;
}
document.getElementById('filter').addEventListener('click', function(e) {
var o2 = document.getElementById("output2");
o2.innerHTML = getFormValues(document.forms[0], ['chair','car','house','tree','flower','grass']);
});
<form><input type="radio" id="chair1" name="chair" class="chair" value="1">
<input type="radio" id="chair0" name="chair" class="chair" value="0" checked>
<input type="radio" id="chair-1" name="chair" class="chair" value="-1">
<input type="radio" id="car1" name="car" class="car" value="1">
<input type="radio" id="car0" name="car" class="car" value="0" checked>
<input type="radio" id="car-1" name="car" class="car" value="-1">
<input type="radio" id="house1" name="house" class="house" value="1">
<input type="radio" id="house0" name="house" class="house" value="0" checked>
<input type="radio" id="house-1" name="house" class="house" value="-1">
<input type="radio" id="tree1" name="tree" class="tree" value="1">
<input type="radio" id="tree0" name="tree" class="tree" value="0" checked>
<input type="radio" id="tree-1" name="tree" class="tree" value="-1">
<input type="radio" id="flower1" name="flower" class="flower" value="1">
<input type="radio" id="flower0" name="flower" class="flower" value="0" checked>
<input type="radio" id="flower-1" name="flower" class="flower" value="-1">
<input type="radio" id="grass1" name="grass" class="grass" value="1">
<input type="radio" id="grass0" name="grass" class="grass" value="0" checked>
<input type="radio" id="grass-1" name="grass" class="grass" value="-1">
<div> <input type="button" value="Search" id="filter"/> </div>
</form>
<div id="output2"></div>

The thing you need to do is break the code up into reusable chunks. So make a method to get the value. That will reduce a lot of code. After than, you should look at a way to reduce how many elements you need to list. Finally, find an easy way to fetch all the values.
So below is code that does this. It uses a helper method to get the elements, find the value. Than it uses an array to know what element groups to look for. And finally it uses map to iterate over the list so you do not have to code multiple function calls.
function getSelected (radioBtnGroup) {
// get the elements for the radio button group
var elms = document.getElementsByName(radioBtnGroup)
// loop over them
for(var i=0; i<elms.length; i++) {
// if checked, return value and exit loop
if (elms[i].checked) {
return elms[i].value
}
}
// if nothing is selected, return undefined
return undefined
}
// list the groups you want to get the values for
var groups = ['rb1', 'rb2', 'rb3', 'rb4']
// call when you want to get the values
function getValues () {
// use map to get the values of the rabio button groups.
// map passes the index value as the first argument.
// code is map(function(k){return getSelected(k)})
var results = groups.map(getSelected)
//displat the results
console.log(results);
}
document.querySelector('#btn').addEventListener('click', getValues);
<form>
<fieldset>
<legend>Item 1</legend>
<label><input type="radio" name="rb1" value="1-1"> One</label>
<label><input type="radio" name="rb1" value="1-2"> Two</label>
<label><input type="radio" name="rb1" value="1-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 2</legend>
<label><input type="radio" name="rb2" value="2-1"> One</label>
<label><input type="radio" name="rb2" value="2-2"> Two</label>
<label><input type="radio" name="rb2" value="2-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 3</legend>
<label><input type="radio" name="rb3" value="3-1"> One</label>
<label><input type="radio" name="rb3" value="3-2"> Two</label>
<label><input type="radio" name="rb3" value="3-3"> Three</label>
</fieldset>
<fieldset>
<legend>Item 4</legend>
<label><input type="radio" name="rb4" value="4-1"> One</label>
<label><input type="radio" name="rb4" value="4-2"> Two</label>
<label><input type="radio" name="rb4" value="4-3"> Three</label>
</fieldset>
<button type="button" id="btn">Get Results</button>
</form>
Personally I would not store the values in an array, I would use an object with key value pairs.
var results = groups.reduce(function (obj, name) {
obj[name] = getSelected(name)
return obj
}, {});

Related

calculate button question, html and javascript

i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />

JS function resets after completion

I have a small form designed to calculate a score based on the answers given. Everything works, the variables are shown in the variables and also shown in the html for a split second. However, after a split second, the function resets and the resulting var is also removed. In trying to understand, I think it has to do with the scope of the var or form behavior? Here is a snippet:
</head>
<body>
<form id="calculateChangeForm" name="calculateChangeForm">
<p><strong>1. To what extend does the change impact the organization?</strong></p>
<input id="q1a1" name="q1" type="radio" value="2"> <label for="q1a1">A specific department or a working group</label><br><input id="q1a2" name="q1" type="radio" value="6"> <label for="q1a2">One department </label><br><input id="q1a3" name="q1" type="radio" value="7"> <label for="q1a3">Several departments</label><br><input id="q1a4" name="q1" type="radio" value="8"> <label for="q1a4">Whole organization</label><br><input id="q1a5" name="q1" type="radio" value="8"> <label for="q1a5">Cross entities</label><br><input id="q1a6" name="q1" type="radio" value="9"> <label for="q1a6">Regional Impact</label><br><input id="q1a7" name="q1" type="radio" value="10"> <label for="q1a7">Group Impact</label><hr class="mb-5 mt-5">
<p><strong>2. How many employees are impacted? </strong></p>
<input id="q2a1" name="q2" type="radio" value="1"> <label for="q2a1"> < 10 </label><br><input id="q2a2" name="q2" type="radio" value="4"> <label for="q2a2">10 - 50 </label><br><input id="q2a3" name="q2" type="radio" value="7"> <label for="q2a3">51 - 100</label><br><input id="q2a4" name="q2" type="radio" value="8"> <label for="q2a4">101 - 200</label><br><input id="q2a5" name="q2" type="radio" value="9"> <label for="q2a5">201 - 500</label><br><input id="q2a6" name="q2" type="radio" value="10"> <label for="q2a6"> > 500 </label><br><br><button id="calculateChangeButton" class="button">Submit</button>
<script> document.getElementById("calculateChangeButton").onclick = function() {calculateChange();}; </script>
</form><hr class="mb-5 mt-5"></div>
<p>Your score is: <span id="changeScore"></span></p>
<script>
var changescore = 0;
function calculateChange(){
var val1 = 0;
for( i = 0; i < document.calculateChangeForm.q1.length; i++ ){
if( document.calculateChangeForm.q1[i].checked == true ){
val1 = document.calculateChangeForm.q1[i].value;
alert("The value of Question 1 answer is: " + val1);
}
}
var val2 = 0;
for( i = 0; i < document.calculateChangeForm.q2.length; i++ ){
if( document.calculateChangeForm.q2[i].checked == true ){
val2 = document.calculateChangeForm.q2[i].value;
alert("The value of Question 2 answer is: " + val2);
}
}
var changescore = parseInt(val1) + parseInt(val2);
alert("The total score: " + changescore);
document.getElementById("changeScore").innerHTML = changescore;
}
</script>
</body>
Thank you,
After input from user t348575, it was clear that the button should be changed to a an input type="button" in order to stop the form from being submitted:

How Do I count the selected checkbox in AngularJS?

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

Sum split values from HTML form, use as data for Google scatter chart

I am creating an online quiz and want be able to plot the score on a chart.
I am attempting to add all the comma separated values in the checked radio buttons of a form in such a way that the result is also a comma separated value, however I am unsure how to do this.
Example:
2,2 + -2,2 + 1,-1 = 1,3
I then want to insert the resulting number into the Google Visualisation API to draw a chart on the same page, preferably updated as each radio button is checked.
Sample form code:
<form>
<input type="radio" name="q1" class="option" value="2,-2" />
<input type="radio" name="q1" class="option" value="1,-1" />
<input type="radio" name="q1" class="option" value="0,0" />
<input type="radio" name="q1" class="option" value="-1,1" />
<input type="radio" name="q1" class="option" value="-2,2" />
<input type="radio" name="q2" class="option" value="2,-2" />
<input type="radio" name="q2" class="option" value="1,-1" />
<input type="radio" name="q2" class="option" value="0,0" />
<input type="radio" name="q2" class="option" value="-1,1" />
<input type="radio" name="q2" class="option" value="-2,2" />
</form>
Google Visualisation API:
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['',''],
[0,0]
]);
var options = {
hAxis: {minValue: -94, maxValue: 94, gridlines: {count:0}},
vAxis: {minValue: -94, maxValue: 94, gridlines: {count:0}},
legend: 'none',
colors: ['#000000'],
width: 500,
height: 500
};
var chart = new google.visualization.ScatterChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
I have been looking for a way to accomplish this however so far none of the solutions I have found are suitable. Any help would be appreciated, thank you.
I made this Fiddle example to show you how to sum comma separated values dinamically. Once you get the values you can plot the result with Google Visualization API.
$(document).ready(function(){
var radios = $('input[type=radio]');
var evalResult = function(){
var sum1 = 0;
var sum2 = 0;
var q1 = $("input[type=radio][name=q1]:checked").val();
var q2 = $("input[type=radio][name=q2]:checked").val();
var values_q1 = q1.split(',');
var values_q2 = q2.split(',');
sum1 = parseInt(values_q1[0]) + parseInt(values_q1[0]);
sum2 = parseInt(values_q1[1]) + parseInt(values_q2[1]);
$(".expression").html(q1+" + "+ q2 + " = "+ sum1 + ","+sum2);
}
evalResult();
radios.change(evalResult);
});
EDIT
You can generalize the procedure over n questions.
$(document).ready(function(){
var radios = $('input[type=radio]');
var evalResult = function(){
var numQuestions = 80;
var sum1 = 0;
var sum2 = 0;
var expr_str = '';
for(var i = 1; i <= numQuestions; i++){
var q = $("input[type=radio][name=q"+i+"]:checked").val();
var value = q.split(',');
sum_1 += parseInt(value[0]);
sum_2 += parseInt(value[1]);
expr_str += (i <= numQuestions) ? q + " + " : q + " = ";
}
$(".expression").html(expr_str);
}
evalResult();
radios.change(evalResult);
});
I think following code should do the job
var totalVal = $(':checked')
.map(function() { return $(this).val(); })
.toArray()
.reduce(function(sum, val) {
var splitVal = val.split(',');
sum[0] = sum[0] + parseInt(splitVal[0], 10);
sum[1] = sum[1] + parseInt(splitVal[1], 10);
return sum;
}, [0, 0]);
console.log(totalVal)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
<form>
<input checked type="radio" name="q1" class="option" value="2,-2" />
<input type="radio" name="q1" class="option" value="1,-1" />
<input type="radio" name="q1" class="option" value="0,0" />
<input type="radio" name="q1" class="option" value="-1,1" />
<input type="radio" name="q1" class="option" value="-2,2" />
<input type="radio" name="q2" class="option" value="2,-2" />
<input checked type="radio" name="q2" class="option" value="1,-1" />
<input type="radio" name="q2" class="option" value="0,0" />
<input type="radio" name="q2" class="option" value="-1,1" />
<input type="radio" name="q2" class="option" value="-2,2" />
</form>

How to Validate Multiple radio buttons

How can I validate multiple radio buttons. All these radio buttons generated dynamically.
<input type="radio" name="answer_option1" value="1" id="ans_options1" />
<input type="radio" name="answer_option1" value="2" id="ans_options2" />
<input type="radio" name="answer_option1" value="3" id="ans_options3" />
<input type="radio" name="answer_option1" value="4" id="ans_options4" />
<input type="radio" name="answer_option2" value="5" id="ans_options5" />
<input type="radio" name="answer_option2" value="6" id="ans_options6" />
<input type="radio" name="answer_option2" value="7" id="ans_options7" />
<input type="radio" name="answer_option2" value="8" id="ans_options8" />
<input type="radio" name="answer_option3" value="9" id="ans_options9" />
<input type="radio" name="answer_option3" value="10" id="ans_options10" />
<input type="radio" name="answer_option3" value="11" id="ans_options11" />
<input type="radio" name="answer_option3" value="12" id="ans_options12" />
<input type="radio" name="answer_option4" value="13" id="ans_options13" />
<input type="radio" name="answer_option4" value="14" id="ans_options14" />
<input type="radio" name="answer_option4" value="15" id="ans_options15" />
<input type="radio" name="answer_option4" value="16" id="ans_options16" />
Try this http://jsfiddle.net/aamir/r9qR2/
Since each group has different name attribute so you have to do validation for each set of radio buttons.
if($('input[name="answer_option1"]:checked').length === 0) {
alert('Please select one option');
}
If you have unlimited number of groups. Try this http://jsfiddle.net/aamir/r9qR2/2/
//Make groups
var names = []
$('input:radio').each(function () {
var rname = $(this).attr('name');
if ($.inArray(rname, names) === -1) names.push(rname);
});
//do validation for each group
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length === 0) {
console.log('Please check ' + name);
}
});
If you want to show just 1 error for all groups. Try this http://jsfiddle.net/aamir/r9qR2/224/
try this new fiddle http://jsfiddle.net/Hgpa9/3/
$(document).on("click","#validate", function() {
var names = [];
$('input[type="radio"]').each(function() {
// Creates an array with the names of all the different checkbox group.
names[$(this).attr('name')] = true;
});
// Goes through all the names and make sure there's at least one checked.
for (name in names) {
var radio_buttons = $("input[name='" + name + "']");
if (radio_buttons.filter(':checked').length == 0) {
alert('none checked in ' + name);
}
else {
// If you need to use the result you can do so without
// another (costly) jQuery selector call:
var val = radio_buttons.val();
}
}
});
var names = []
$('input[name^="answer_option"]').each(function() {
var rname = $(this).attr('name');
if ($.inArray(rname, names) == -1) names.push(rname);
});
$.each(names, function (i, name) {
if ($('input[name="' + name + '"]:checked').length == 0) {
console.log('Please check ' + name);
}
});

Categories

Resources