update div with values of radio buttons on page load - javascript

I need to collect the values of the checked radio buttons on page load (they are checked on page load) and add them and not only when the user clicks a radio button.
Here's the javascript:
$(function ()
{
updateDivResult();
$('input:radio').live('click',updateDivResult);
$('#1').click();
})
function updateDivResult(){
if ($("input:radio:checked"))
{
price = parseFloat($(this).val());
$('#price').html(roundNumber(price,2));
}
};
roundNumber() is a function defined by me.
Now it only updates the #price div when the user clicks a radio button.
Also, there are a few groups of radio buttons - how do I only add the value of one radio button from the group to the total price?
Thank you for assistance.

I think you need to loop through the checked values rather than just getting the val() of that selector because it seems like there could be more than one checked.
function updateDivResult(){
var price = 0;
$(":radio:checked").each(function(){
price += parseFloat($(this).val());
});
$('#price').html(roundNumber(price,2));
};

Can you provide more details?
I can see you are using jQuery.
You could use
$(document).ready(function() {...});
to run some methods when the document is read.
Moreover you could put a specific class to your html elements and use the "each" function to traverse them.
e.g.
$('.your_el').each(function() {...});
In that case the handler will be executed on each object with the class "your_el".
Hope this help, even if the problem is not so clear to me.
Che

Related

How to find radio group checked property

Here, I've three radio group in a single page. But in the entire page I want to select only one radio option. Like if I'm selecting Monday then Tuesday selection should be unchecked automatically. How can I proceed with the logic, below logic is not working as expected.
sample JSON :
{
report:[
{
day:'Monday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Tuesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
},{
day:'Wednesday',
slot:[
'9-10am',
'10-11am',
'11-12am'
]
}
]}
JS code
for(var I=0; I<reports.length; I++){
var radios = document.getElementsByTagName('input')
if(radios[I].type === 'radio' && radios[I].checked){
document.getElementById(radios[I].id).checked = false
}
If you're able to create radio buttons in SurveyJS, you should be able to give the button group a name, so there would be no need for any additional JavaScript. Check out their documentation for an example.
Looks like the sort of nested structure you have for the buttons could be achieved with something like a dynamic panel or cascading conditions in SurveyJS. You should be able to render the available time slots dynamically with "visibleIf" based on the selected day.
I would definitely dig around the documentation of SurveyJS to find a solution there rather than hacking your way around it. But solely as an exercise, the problem in your current code could be that you're selecting a button by ID, which will not work correctly if you have tried to give the same ID to multiple buttons. After all, you already have the target button as radios[I], so you could just use radios[I].checked = false. Or the issue could be that you're unchecking the selected button AFTER the new selection has been made, which might actually uncheck the button you just clicked. Hard to say without additional information, but in any case, looping your inputs based on a value that might be something else than the actual number of inputs (you're using reports.length) is probably not the best idea, since that value might be different from the number of inputs in your form, which would mean that not all of them are included in the loop. Here are a couple of examples of what you could do instead:
// Get all radio buttons
const radioButtons = document.querySelectorAll('input[type="radio"]')
// If you need to uncheck the previously selected one (don't do this if you can avoid it!)
radioButtons.forEach(radioButton => {
// Use a mousedown event instead of click
// This gives you time to uncheck the previous one before the new one gets checked
radioButton.addEventListener('mousedown', () => {
// Get the currently selected button and uncheck it
const currentlySelected = document.querySelector('input[type="radio"]:checked')
if (currentlySelected) currentlySelected.checked = false
})
})
// You can add further options to the querySelector, such as [name]
// This gets the currently selected button in the specified group
const checkedRadioButton = document.querySelector('input[type="radio"][name="group-name"]:checked')
Here's a fiddle demonstrating this sort of "fake" radio button functionality (without a "name" attribute).
You can give all these radio buttons the same name, then one radio only will be checked.

Getting value from mdl radio button

In the following code why doesn't the radio report the correct value when checked via its variable name?
var $myRadio = $('input[type=radio][name=options]:checked');
$('#button').click(() => {
// this works
console.log($('input[type=radio][name=options]:checked').val());
// this doesn't :(
console.log($myRadio.val());
});
https://jsfiddle.net/charsi/p4beztwx/13/
I am using mdl radio buttons so that could be causing it. I have also tried getting the value with $myRadio[0].MaterialRadio.value but that doesn't work either.
EDIT: This was a poorly worded question and didn't really have anythng to do with mdl. What I really wanted was the ability to set the DOM variable for my radio button somewhere else without having to select it by name again to check the value.
The reason for getting incorrect values when checked via its variable name is because you are setting $myRadio before the click event. $myRadio is set on document ready (before click event) and it gets the value of the checked radio option which at this moment is always 1.
Moving $myRadio inside a click handler should work. Why? Because now it gets the value of the radio (checked) as soon as the click function is called which is actually what you need.
$('#button').click(() => {
var $myRadio = $('[id^="option"]:checked');
// neither of these work
alert($('input[type=radio][name=options]:checked').val());
alert($myRadio.val());
});
fiddle here
For anyone else running into the same issue. Not wanting to call the radio button name when checking for its value, you can use filter -
var $myRadio = $('input[type=radio][name=options]');
$('#button').click(() => {
console.log($myRadio.filter(':checked').val());
}

JQuery getting the closest element and filtering children

I have 3 forms with IDs ( form1 , form2 , form 3). every form has its own different drop down lists (drop1, drop2) and submit button.
When you click submit button in every form . It checks which option (in the drop down list of the same form) is selected . To find the exact selected Option I use this code :
$(".submitButton").each(function(){
$( this ).click(function(){buttonAddClicked(1)});
});
function buttonAddClicked(FormID){
$('form'+ FormID +' *').filter('.MyDropDownList').each( function(){
var selOption=$(this).find('option:selected');
}
Till now everything is working fine. I get the selected option with no problems at all.But, when I make some modifications problems happens.
On document ready, I copy form1 html . So, form1 is duplicated with the same id.
--Let's say that I have form1A , form1B--
When I press submit button in form1A or form1B the code always go to the selected option in form1A. This problem is killing me .
How can I modify my code to catch the form closest form . I tried some techniques but didn't work . The problem is in using ('*') with filter with closest.
Or if There's another solution to solve this I would be very thankful for you guys .
Thank you .
Edit: I can Get the closest form easily , but how to loop (each) on that form Drop-Down-Lists,
The problem is for all button clicks you are passing 1 as the form id.
There is no need for that, assuming the button is within the form then, you can use .closest() to find the form which contains the button then use .find() to find the select element and .val() to find its selected value as shown below
jQuery(function () {
$(".submitButton").click(function () {
var $form = $(this).closest('form');
var selectedValue = $form.find('.MyDropDownList').val();
//do whatever you want to do with the selectedvalue
//if you have multiple elements and wants to have an array of values
var selectedValues = $form.find('.MyDropDownList').map(function () {
return $(this).val()
}).get();
});
})
First, you should never have duplicate IDs in the document. It causes problems with assistive technology. So the best solution is to modify the ID when you duplicate the form.
However, you can use jQuery's closest to find the closest parent http://api.jquery.com/closest/
function buttonAddClicked(){
var selOption = $(this).closest('form').find('.MyDropDownList').val();
}

Access hidden checkboxes with javascript and jQuery

I have a datatable, where each row has a checkbox. I'm trying to add select-all functionality to this set of checkboxes, for which I created the following function:
function selectAll() {
$(':checkbox').each(function() {
this.checked = true;
});
}
This works to select all checkboxes which are currently visible, however, the checkboxes on other pages of the datatable are not selected. I know that there is an issue with these checkboxes in general, since to submit the form and include those checkboxes, I had to add the following function:
$('form').submit(function() {
oTable1 = $('#mytable').dataTable();
$(oTable1.fnGetHiddenNodes()).find('input:checked').appendTo(this);
});
So I suspect that in order to check these checkboxes, I will somehow have to append them to the DOM, at least temporarily, check them off, and then remove them from the DOM. Or is there something simpler that I can do?
I managed to get this work using the following:
oTable1 = $('#mytable').dataTable();
$(oTable1.fnGetNodes()).find(':checkbox').attr('checked',true);
As an alternative, you can also use
$(oTable1.fnGetFilteredNodes()).find(':checkbox').attr('checked',true);
which will apply the "select-all" only to the rows that match the current filter.

Javascript tickbox validation

I am trying to add javascript validation to a bunch of check boxes, basically what I want is as soon as the user has selected 3 tickboxes, it should disable all of the tickboxes except the three that were ticked.
How could I go about doing that?
Thanx in advance!
The following will disable the rest of the checkboxes if you select 3 of them, and also enable them once you uncheck one of the three selected..
$(':checkbox').click(
function(){
var selected = $(':checkbox:checked').length;
if (selected == 3)
{
$(':checkbox:not(:checked)').attr('disabled',true);
}
else
{
$(':checkbox:not(:checked)').attr('disabled',false);
}
}
);
Live demo
Have on onclick handler that when a checkbox is clicked it ups a counter by one if it is unchecked it decreases the count. After raising the count, test to see if it is three. Then probably the easiest method is to either save the ids of the three checked boxes or save them in the previous step. Then change the click event to return true only if the ids match the saved ids.
Sorry I don't have time right now to actually write up any code. Hopefully this will get you started.
jQuery
$("#container :checkbox").click(function(){
if ($("#container :checkbox").length >= 3) {
$("#container :checkbox").attr("disabled", "disabled");
}
});

Categories

Resources