function to push value to array on checkbox OR radio change - javascript

I have a function like this:
$('input:checkbox').change(function() {
array = [];
$('input:checkbox:checked').each(function() {
array.push($(this).val()); // push checked checkbox values to array
});
$('input:radio:checked').each(function() {
array.push($(this).val()); // push checked radio values to array
});
someOtherFunction();
});
... which collects values from checkboxes and radio buttons in one array. At the moment it runs when a checkbox changes but I want it to run when a radio button changes too.
As a noob I have no idea where to start so have tried very little. And I didn't find the answer after a good search.
Thanks in advance.

Try with
$('input:checkbox, input:radio').change(function() {
The problem is that your current selector is only applicable for checkboxes.

Related

How to accumulate a score/value based on the choices selected on a form using jQuery

I wanna to try to researching around on how to achieve this but I am not sure about how to make the solution for this.
Basically I have a form that contains some select list, radio buttons, and checkboxes. Each option on the form has a corresponding numeric value that will be accumulated and displayed to the user when the form gets submitted.
What I am not sure about is how to be able to add or deduct a value if the user chooses to change the a choice on the form.
For example, when a user is on the first dropdown element, and they choose option 2 which has a value of 5 then the current accummulated value us 5. Then on question 2, they choose option 1 which has a value of 2 which makes the accummulated value 7. Then the user changes the answer for question one from option 2 to option one which means 5 will be deducted from the accumulated value and 2 will be added since it is the value for option 1 which changes the accumulated value to 4.
I know the description I mentioned might be all over the place but I hope it makes sense.
I am trying to use jQuery and so far, my approach would be to check if any of the form element's value has changed:
(function($) {
var score = 0;
$(".the-form #step-5 :input").change(function() {
console.log($(this).val());
});
})(jQuery);
But I can't seem to figure out how to get the previous value of the option that was selected if the user changes their answer.
Any suggestion would be appreciated.
Can you recalculate across the whole form each time the user changes any of the elements?
$(".the-form :input").change(calculateChanges);
function calculateChanges() {
// Retrieve the current values of all elements and add them together
}
When a user submits, then start doing the calculations or when a select is changed, i.e. attach it to the event. Score is now a local variable
function calcValue() {
var score = 0;
//select all the elements using example below
$(".the-form :input").each(function( index ) {
//i forgot jQuery exact syntax but $(this).val or //$(this).val()
score += $( this ).val();
});
console.log(score);
}
In this case you can attach it to the submit
function submit() {
var score = calcValue();
}
Or you can put it in a change event of a select
function selectChanged() {
var score = calcValue();
}

How to get value of radio button group in jQuery?

I couldnt find the right answer for my case.
var inputs = $("root :input[typeof]");
// looping thru elements
inputs.each(function(index) {
var name = $(this).attr('name'); // get element by name (or by id)
var value = $(this).val(); // get element value
// How do I capture radio button (or checkbox) group
// element in this loop? And how do I get a checked value of such group?
// Note, in here $(this) should be the radio button group element
}
So, the question is in code comment.
How inside that loop get a value of radio button group element?
In HTML if you refer to such group by name you will automatically get the value of checked radio button in that group.
How do you do that in jQuery, when $(this) is current element in the loop?
Thanks
// Note, in here $(this) should be the radiobutton-group element
if that's the case, then this will find the value of the radio button that is checked:
$(this).find('input:checked').val();
Here is a function to check the radio inputs:
function CheckRadioList() {
$('input:radio').each(function () {
// your code here, you can storage them or do what you want.
console.log($(this).prop('checked'));
});
}
Here is a demo if you want test it: http://jsfiddle.net/jpmbL49r/
name: $(this).attr('name');
id: $(this).attr('id');
checked: $(this).prop('checked')
I hope it's helps!

Problem adding and removing in array with jquery and checkboxes

I got a problem when I try to create an array of checked checkboxes.
The checkboxes are generated dynamically with an "onChange" attribute that calls the javascript function to add or remove in the array. The function gets "talla" that it is the value to add or remove.
This is my javascript code for the function: (arrayTallas is global)
function checkbox_marcado(talla)
{
if(jQuery('#id_talla').is(':checked') == true)
{
arrayTallas.push(talla);
}
else //elimina posicion del array al deseleccionar un checkbox
{
var index = arrayTallas.indexOf(talla);
arrayTallas.splice(index,1);
}
}
The problem is that the first checkbox work fine, but the others are not deleted.
For example. If a have 3 checkboxes with values "1" "2" "3" if I click on the first one, it is added normally, and if I click again on it, it is deleted normally too... but if I click on the first one, and then on the second one, when I click again on the second one to delete it from the array, when I print the array this is what I get: 1 2 2
Thanks
If you're using jQuery anyway, why not use a function like this:
$('#tallas').live('click', function(){
$(':checkbox:checked').map(function() {
return this.value;
}).get().join(',');
});
I think you mean to say:
jQuery('#id_' + talla)
where you're saying:
jQuery('#id_talla')
Also check to make sure you don't have multiple checkboxes with the same id attribute.

From HTML Form to XML Tree

I would like to pick some of your brains on this matter...
I've got a large form where there are a lot of multiple selection choices. Some are radio groups and yet others are "select all that apply" checkbox groups.
I'm trying to figure out the best way to translate each of these selections within my XML tree to send to the SQL server.
For radio groups, that's easy... one is selected: option = id #
But for checkboxes, this is a little different... I'd like to stick to sending 1 or 0 for selected or not selected. But checkbox dont have a value and so I have to check to see whether or not it's selected: true or false/yes or no.
What do you think would be the best way to convey whether or checkbox within a group of checkboxes has been selected within the XML tree?
One way (and the simplest) would be to send only those checked and the server will assume the others are not checked. The other way would be to iterate over your form elements, select the checkboxes and see if they are checked or not, one by one. Something like:
var checkboxes = []; // assoc array of all checkboxes
function formValidate(form)
{
var list = form.getElementsByTagName('input')
for (var i in list)
{
var elem = list[i];
if (elem.type == 'checkbox')
checkboxes[elem.name] = elem.checked;
}
return true; // assuming this is an onSubmit event
}
and in your HTML:
<form onSubmit="return formValidate(this)" ...

jQuery see if any or no checkboxes are selected

I know how to see if an individual checkbox is selected or not.
But Im having trouble with the following - given a form id I need to see if any of the checkboxes are selected (i.e 1 or more), and I need to see if none are selected. Basically I need two separate functions that answer these two questions. Help would be appreciated. Thanks!
Actually, I would just need a function to tell me if none are selected. Knowing this would answer the other question.
You can use something like this
if ($("#formID input:checkbox:checked").length > 0)
{
// any one is checked
}
else
{
// none is checked
}
JQuery .is will test all specified elements and return true if at least one of them matches selector:
if ($(":checkbox[name='choices']", form).is(":checked"))
{
// one or more checked
}
else
{
// nothing checked
}
You can do this:
if ($('#form_id :checkbox:checked').length > 0){
// one or more checkboxes are checked
}
else{
// no checkboxes are checked
}
Where:
:checkbox filter selector selects all checkbox.
:checked will select checked checkboxes
length will give the number of checked ones there
Without using 'length' you can do it like this:
if ($('input[type=checkbox]').is(":checked")) {
//any one is checked
}
else {
//none is checked
}
This is what I used for checking if any checkboxes in a list of checkboxes had changed:
$('input[type="checkbox"]').change(function(){
var itemName = $('select option:selected').text();
//Do something.
});
Rahul's answer is best fit for your question. Anyway, if you have a group of checkboxes to be checked and not all the checkbox in your form, you can go for it.
Put a classname for all the checkboxes you want to check, say for example, a classname test_check and now you can check if any of the checkbox is checked belonging to the group by:
$("#formID .test_check:checked").length > 0
If it returns true, assume that one or more checkboxes are checked having the classname test_check and none checked if returns false.
Hope it helps someone. Thanks :)-
You can do a simple return of the .length here:
function areAnyChecked(formID) {
return !!$('#'+formID+' input[type=checkbox]:checked').length;
}
This look for checkboxes in the given form, sees if any are :checked and returns true if they are (since the length would be 0 otherwise). To make it a bit clearer, here's the non boolean converted version:
function howManyAreChecked(formID) {
return $('#'+formID+' input[type=checkbox]:checked').length;
}
This would return a count of how many were checked.
This is the best way to solve this problem.
if($("#checkbox").is(":checked")){
// Do something here /////
};

Categories