Loop through radio groups in javascript - javascript

I am trying to loop through Radio groups and validate that the user has made a selection using Javascript. The radio groups are dynamic so the field names are unknown at runtime, and the number of radio groups will also be unknown. After the user has made a selection for each radio group, then process the form.

You can have a map to find the field names that are not checked.
function add() {
remaining[this.name] = true;
}
function remove() {
delete remaining[this.name];
}
var form = $(this), remaining = {};
form.find(':radio').each(add).filter(':checked').each(remove);
Then the remaining variable will be an object that holds the names of the radio group that the user hasn't checked.
If it is an empty object, then the user has selected all groups.
For a working example, look here: http://jsfiddle.net/thai/qtJsJ/1/

You could select all radio buttons using the 'input:radio' selector and then make sure that for each distinct name a value is set.
$(document).ready(function() {
$(this).find("input:radio").each(...)
}

with pure javascript you could try something like
var elements = document.getElementsByTagName("input");
for(var i = 0; i<elements.length; i++)
{
if(elements[i].type === "radio")
{
//dostuff
}
}

Related

Check duplicate value in array and add if doesn't exist using jquery

I have a form where user can fill details and on clicking of add attendee button can add up to 9 people details. I am getting value of user name, selected checkbox item id and item quantity and storing inside array and passing these values in url to add selected items and created user On first click but when i click second or third or multiple times its adding duplicate value inside array. I want to check if values exist or not if its there need to increase quantity and doesn't want to add it again in array.
Here is my code
jQuery(document).ready(function() {
var allVals = [];
jQuery("#btnadd2").click(function() { //Clicking on this add attendee button getting values
var nameatt = jQuery("#txtAttendeeNames").val();
var qty = jQuery('input[name="qty"]').val(); //increase quantity if selected checkbox id is already present in array
jQuery(".big:checked").each(function() {
allVals.push($(this).val()); //getting selected checkbox value and based on this getting item id which should not exist in array
});
for (i = 0; i < allVals.length; i++) { //creating url and updating multi div with this
var rslt = allVals.join(','
'+'
custcol_name_of_attendees | '+nameatt+' | +';');
rslt = jQuery('#multi').val(rslt);
}
});
});
Use jQuery.inArray() in jquery. The jQuery.inArray() method is similar to JavaScript's native .indexOf() method in that it returns -1 when it doesn't find a match. If the first element within the array matches value, jQuery.inArray() returns 0.
jQuery(".big:checked").each(function() {
if(jQuery.inArray($(this).val(), allVals) == -1) {
allVals.push($(this).val());
} else {
// Already present in the array
}
});

Radiobutton .val() returns not null value even if none of radiobuttons is selected

I have 3 groups of radiobuttons, all of them properly named. On submit() I want to check if user selected option from each of groups.
I do that that way:
$('.form').submit(function(){
var selectedUser = $('input[name="selectedUser"]').val();
var searchType = $('input[name="shareType"]').val();
var selectedSearch = $('input[name="selectedSearch"]').val();
console.log(selectedUser, searchType, selectedSearch);
return false; //for testing purposes
});
The problem is that each of three variables return not null values even if none of radiobuttons is selected.
Fact that might be important: each of groups contains more than 1 radiobutton, each radiobutton has distinct value.
You need to test if the radio is selected, you can do this using the :checked pseudo-selector:
var selectedUser = $('input[name="selectedUser"]:checked').val();
var searchType = $('input[name="shareType"]:checked').val();
var selectedSearch = $('input[name="selectedSearch"]:checked').val();
if(selectedUser || searchType || selectedSearch) {
// At least one selected
}
else {
// None selected
return false;
}
Here is a fiddle which demonstrates.

adding radio button values in separate groups using javascript

I have a form with radio buttons that I'm using javascript to loop through and return the sum of all the radio buttons to an input element at the bottom of the page. The script I'm using is this and it works fine.
<script type="text/javascript">
function checkTotal() {
var radios = document.querySelectorAll('input[type=radio]'),
sumField = document.querySelector('input[type=text]');
var sum = 0;
for (var i = 0, len = radios.length - 1; i <= len; i++) {
if (radios[i].checked) {
sum += parseInt(radios[i].value);
}
}
sumField.value = sum;
}
</script>
Here's my form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire.htm
However I need to build another form where there are several questions in different groups and I need to sum the totals for each group separately and post them to their corresponding input elements on the page accordingly. Here's my new form http://cognitive-connections.com/Prefrontal_Cortex_Questionnaire100913.htm
I'm not an advanced javascript user but do have a pretty good understanding of programming itself (I think, lol) My head tells me that I should be able to simply declare a unique var for each different group and a unique element to post it's results to and use the same loop (with correct vars for each group) for each group. But when I add [name="elements name"] as the identifier for the document.querySelectAll it grabs the elements with that name only and if I name the elements themselves the same name the radio buttons loose their inherent property of only letting one radio button per question be selected at a time? I've also tried creating a class id for each group and tried to use it as the identifier in the document.querySelectAll and it doesn't seem to work at all then. Any help is greatly appreciated..
As per my understanding of question, below is my answer. And here is the fiddle http://jsfiddle.net/8sbpX/10/.
function enableQ(cls) {
var ele = document.querySelectorAll('.' + cls)[0],
ev = (document.addEventListener ? "#addEventListener" : "on#attachEvent").split('#');
ele[ev[1]](ev[0] + "change", function () {
var radios = ele.querySelectorAll('[type="radio"][value="1"]:checked').length;
ele.querySelector('[type="text"]').value = radios;
});
}
enableQ("rad-grp");

Getting value of selected checkbox with jquery from checkboxes without id's

I have a number of checkboxes that are generated from a JavaScript API call from a database. I need to be able to pass the values of the checkboxes which are then selected by the user, and sent to the processing page. The issue is that the checkboxes don't have ID's associated with them(or this wouldn't be a problem) They all have the same name, but no ID's.
What is the best way to find which check boxes are selected, and pass their values to the following page?
One way I started was with an array:
var options = ["option1","option2","option3"];
var option 1 = [0];
var option 2 = [1];
var option 3 = [2];
On the processing page, using:
var option1 = getFromRequest('option1') || '';
var option2 = getFromRequest('option2') || '';
var option3 = getFromRequest('option3') || '';
Is there a better way of doing this?
I've changed the implementation to the following:
var values = []
$("input:checkbox.subIndustry").each(function(){
values.push(this.value);
});
passing the values to the success page with
window.location.href = REGISTER_SUCCESS +'&values='values.join(",")
which should then get the value with
var variablname = getFromRequest('values') || "";
This is returning Undefined. Any help?
An easy way to select them would be something like $("input[type=checkbox]:checked")
However, if you wanted to keep up with them as they are checked, even if they are added after you load, you could create a variable, then asign a delegation to the "change" state of each input that is a checkbox and update this variable on each change.
It's as simple as:
var checked, checkedValues = new Array();
$(function() {
$(document).on("change", "input[type=checkbox]", function(e) {
checked = $("input[type=checkbox]:checked");
// if you wanted to get an array of values of the checked elements
checkedValues = checked.map(function(i) { return $(this).val() }).get();
// make a string of the values as simple as joining an array!
var str = checkedValues.join(); // would return something like: value1,value2,ext...
});
})
Working Example
Since all your checkboxes have the same name, you can retrieve the checked ones using a variation of:
var checked = $('input[name=ckboxname]:checked');
see: :checked selector for more information
you can simply get the values of checked checkboxes by using
$('input[name=checkboxname]:checked').val();
this will give you the value of checkbox which is checked and for all values simply use
each function of jquery.
Turns out, the answer was to utilize indexOf in the underscore.js library. The solution had to be applied in the API being used to send data.
(_.indexOf(values, '9') != -1 ? 1 : '0'),

copying values from one textbox to another based on the input type id

With reference to the question regarding replicating values from one textbox to another
Replicating the values to another textbox
The solution works well if there are only two text boxes. But it fails when the index is running on loop.
For Ex - let us consider the table has list of text boxes in each row
1st row textbox1 textbox2
2nd row textbox3 textbox4
the id for each box is generated based on the status index. When I update the value in textbox1 textbox2 gets updated. But when I update textbox3 , instead of updating textbox4.textbox2 is updated.
Because the linked code updates textbox2 directly. Put the ids in an array and iterate over it to set the value of each text box, e.g.
function updateTextareas(el) {
var value = el.value;
for (var i=1, iLen=arguments.length; i<iLen; i++) {
document.getElementById(arguments[i]).value = value;
}
}
Then you can call it like:
document.getElementById('input1').onkeyup = function () {
updateTextareas(this,'textbox2','textbox3',...);
};
or some similar strategy.
Give all elements in the set the same name (or classname, and use getElementsByClassName). Then do the following pseudocode in javascript:
// onmodify:
var name = thisTextarea.name;
var newText = thisTextarea.text;
var elementsToUpdate = document.getElementsByName(name);
for each textarea in elementsToUpdate {
if (textarea != thisTextarea) // may not even need this line
textarea.text = newText;
}

Categories

Resources