Adding total of checked Radio Buttons - javascript

UPDATE
If you try the form on this link http://jsfiddle.net/Matt_KP/BwmzQ/ the fiddle and select the top right £40 radio button then see the order total at the bottom it says £40. Then if you select the £75 the order total changes to £75 but then if you go back and check the £40 again the order total is £75 + £40 when it should just be £40 for the radio button that is checked.
UPDATE END
I have a section with Radio buttons where only certain radio buttons can be checked if others are selected. So say if a user selected one Radio Button but then selected another the first Radio Button would become unselected as they cannot have both selected.
Also I am using a custom attribute in the radio buttons called data-price which holds the value of each radio button that needs to be added toghther.
The problem is when a user selects a Radio Button the total shows fine but then if the user selects another radio button that can't have the previous one selected it adds the total onto the previous one where it should only add the Radio Buttons that are checked. It is kind of like caching the totals I think.
This is what I am using to total the checked Radio Buttons:
<script type="text/javascript">
jQuery(document).ready(function($){
$('input:radio').change(function(){
var total = 0.0;
$('input:radio:checked').each(function(){
total += parseFloat($(this).data('price'));
});
$('#total').val(total.toFixed(2));
});
})
</script>

I think the majority of your issues can be circumvented with some new HTML....
Your crazy jQuery code to limit the input is ridiculous.. you have name, value, and your data-price attributes... splitting each radio set up by item seems a little overkill to me..
Here is a limited example (as per our discussion in the chat).
http://jsfiddle.net/CZpnD/ <- here is the example you can work from..
the main things to look at are how I used the same radio name for each "block" of options, and how I loop through all options when a single option is changed to get the new total (not the most efficient but it works).
and for the love of pete use labels!

HTML is build to do this.
<form name="myform">
<input type="radio" name="foo" value="10" /> foo
<input type="radio" name="foo" value="30" /> bar
</form>
If you give radio buttons the same name then only one can be selected.
Further more when you get the radio element the .value property represents the value of the currently checked radio button
var myform = document.forms.myform;
var radio = myform.elements.foo;
var price = radio.value;
Note that radio is a RadioNodeList which is only returned by elements[name]
Example
However it turns out that browser support for RadioNodeList is appaling so you have to do it manually. Or use the RadioNodeList polyfill
for (var i = 0, len = radio.length; i < len; i++) {
var el = radio[i];
if (el.checked) {
var price = el.value;
break;
}
}

Related

how to get unchecked radio button attributes?

I have several checkboxes and radio Buttons with same class that user is able to select one of the radio Buttons and multi checkboxes.
after checking one of them i hold sum of amount by amount attribute in variable
and after unchecked checkbox i reduce amount from sum value
but How to find the radio attributes that is unselect after choosing one of radio buttons to reduce from sum variable?
<input type="radio" class="form-control selected-tuitions" name="selected-tuitions[]" value="70" amount="8600000" allow-count="0" interval="0" section="2" pre-payment="8600000">
you can try this code:
$('input[type="radio"]').not(':checked').each(function(){
//Your Code
});
So the problem will be that only the selected input will be sent in your $_POST, so if you want to access the unselected in PHP it is a bit tricky. You can use jQuery to get the values of the unselected radios, and then store it in a hidden input which will then get posted.
//Add this input to your form
<input type="hidden" name="unselected-tuitions" id="unselected-tuitions">
//When the radio buttons gets clicked
$(document).on('click', '.selected-tuitions' function() {
getUnselectedTuitions()
});
function getUnselectedTuitions() {
let unselectedValues = [];
//Loop through each of the unselected radio items
$( "input.selected-tuitions:not(:checked)" ).each(function(){
unselectedValues.push($(this).val());
});
//Store all the unselected values in our hidden input
$("#unselected-tuitions").val(unselectedValues.toString());
}
So now you will have a hidden input with all the unselected values, which will be in the $_POST variable.

How to disable check box per day and fetch the selected values using Angular.js?

I have one table where some dynamic drop down list is present for 7 days. I have also + button implementation which can create more row dynamically for a day.
For each row I have check box. Here I need for each day user can only check up-to two check box and other will remain disable.
In my case after checked from 2 check box from total table other are becoming disable but here I need to disable per day.
My all working code is present inside: plunkr.
There you can find one Edit button; I need when user will click on edit button the stored data (clicked on store button) will again set on the required field with check box.
My all code is here.
Is this what you require, it's a little hard to understand your question:
So instead of your disabled function:
$scope.chk =[];
$scope.isDisabled = function(dayName) {
var count = 0;
if ($scope.chk[dayName]) {
for (var prop in $scope.chk[dayName]) {
if ($scope.chk[dayName][prop]) count++;
}
}
return count++ === 2;
};
Note the line above the disabled function. And then your html:
<td>
<input type="checkbox"
name="{{d.day_name}}"
value="true"
ng_model="chk[d.day_name][$index]"
ng-checked="answerIsSelected($parent.$index, $index)"
ng-click="toggleAnswerSelected($parent.$index, $index)"
ng-disabled="isDisabled('{{d.day_name}}')" />
</td>
Plunk here: Plunky McPlunk
Seems to do as you ask, disable after 2 goes.
Check this additional link: More insight
For further info

Calculations based on radio button choices

I am using a MEAN stack for my web project. The front end is a simple registration form that asks for several user inputs. For example, it says "how many products are you buying?" The next question is a radio button. It says is this product large or small? My question is the following: the calculation to get the cost of the order is #products*42+(12 if large is selected) or #products*42+(0 if small is selected). How do I code this in javascript(I am using node in my backend). In other words, how do I tell my calculation code that when user selects a radio button you need to add a following number and how do I pass on the number of products typed to my formulas? I have started by assigning value=1 for small and value=2 for large radio button option. Just a general example would be helpful as I can code the details and update the formulas once I get around this problem. Thank you
If you want to do the calculation on the client side and the elements are in an HTML form like:
<h1>Radio Buttons</h1>
<form name="catch-radio" method="post">
<div class="input">
<span class="label">How many products are you buying?</span>
<input id="product-count" type="text" name="product_count" value="0"/>
<br/>
<span class="label">Is this product large or small?</span>
<br/>
<span class="label">Large</span>
<input type="radio" name="product-size" value="12" checked="checked"/>
<br/>
<span class="label">Small</span>
<input type="radio" name="product-size" value="0"/>
</div>
</form>
<div>
<h2>Cost of order:</h2>
<p id="calculation"></p>
</div>
with an input for the number of products (with an id of 'product-count') and radio buttons corresponding to the product size (named 'product-size'), you can calculate the cost and output it to an element on the page (with an id of 'calculation') by adding event handlers to the form fields to register a change in the form, and then from those handlers calling a function to perform the calculation and update the page accordingly like so:
// Cost is the count of products purchased multipled by 42 then added
// to 12 in the case that the product is large, and zero in the case
// that the product is small
function calculate_cost() {
let count = parseInt(document.getElementById('product-count').value);
if (count > 0) {
let size = 0;
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
if (document.getElementsByName('product-size')[i].checked) {
size = parseInt( document.getElementsByName('product-size')[i].value);
break;
}
}
let cost = count * 42 + size
document.getElementById('calculation').innerHTML = cost;
}
}
// handlers for form input change
// call calculate_cost() on change
// note that the text input is an on-change event but for radio buttons
// an onclick handler is needed for each button
for (var i = 0 ; i < document.getElementsByName('product-size').length; i++) {
document.getElementsByName('product-size')[i].onclick = function() {
calculate_cost();
}
}
document.getElementById('product-count').onchange = function() {
calculate_cost();
}
I put up a quick demo of this on CodePen here: http://codepen.io/P1xt/pen/yOKqXP/
The particularly interesting bit is that for the radio buttons, you need to add a click handler for each button separately (and it must be a click not a change handler, and to figure out which radio is currently selected, you need to explicitly check each one to see if it's 'checked'.
Note: If you're looking to do your calculations on the server-side, you'd need to submit the form, then collect the product-count and product-size from the submitted form elements in order to perform the calculation.
Why not use 0 and 12 as the values for the radio buttons, then the backend can just add the selected value?

AngularJS - uncheck radio button

The following JSFiddle allows me to deselect a radio button selection.
http://jsfiddle.net/8s4m2e5e/132/
I'm using AngularJS 1.4 and in one of the posts here, I read that the above JSFiddle doesn't work with angular 1.3+ versions. Thats true, it doesn't work when I implemented the code in the above fiddle. How do I get this functionality to work with my version?
Following is my code.
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="#Model.FieldName"
name="#Model.FieldName"
ng-model="gPA(#Model.Id).value"
value="#((part as BaseInputPartVM).GetStringValue())"
ng-click="uncheck($event, #Model.Id)" />
</div>
}
In my controller,
$scope.uncheck = function (event, partId) {
if ($scope.gPA(partId).value == event.target.value)
$scope.gPA(partId).value = false
}
This code works for deselecting (uncheck) a radio button selection. However, the basic radio button selection doesn't work and I'm not able to select any radios, because the above if condition is always turning to true.
Is there a way I can check for the Previously selected radio value and the new selected value? In order to get the above functionality to work correctly, I need to access both the previous and new radio selected values for comparison. I've looked into ng-model, ng-change and all of them fetches the current radio selected value, but I also need to know the previous selected value as well.
Okay. I think I got an answer to my question... for the input radio, I added ng-mouseup event to capture the previous value of the radio selection before the click. Also, I've added a hidden variable on the page to store this previous radio button selected value. Then in the ng-click event, I will check the previous selected value against the current selected value. If previous and current values are same, I will set the value to null or false, to uncheck the selection.
foreach (var part in Model.ChildParts)
{
<div class="radio col-md-12">
<input type="radio"
id="#Model.FieldName"
name="#Model.FieldName"
ng-model="gPA(#Model.Id).value"
value="#((part as BaseInputPartVM).GetStringValue())"
ng-mouseup = "setPreviousSelectedValue(#Model.Id)"
ng-click="uncheck($event, #Model.Id)" />
</div>
}
<input type="hidden" id="previousRadioSelection" name="previousRadioSelection" ng-model="previousRadioSelection" value="" />
In the controller,
//set previous selected value of radio button
$scope.setPreviousSelectedValue = function (partId) {
$scope.previousRadioSelection = $scope.gPA(partId).value;
}
//uncheck radio button
$scope.uncheck = function (event, partId) {
if ($scope.previousRadioSelection == event.target.value)
$scope.gPA(partId).value = null;
}

Why radio button click event behaves differently

Example on JS FIddle.
The question is:
If the first click is on the radio button, it behaves normally; But if the first click is on span text (i.e. aaaa), it can not get the checked radio.
Please tell me why and how I can make it the same.
This code, which happens when the radio button is clicked:
var obj = $(e.target||e.srcElement).parent();
score = obj.find('input:checked').val();
Puts the parent in the obj variable, which is the containing DIV. This contains both of the radio buttons. It then finds the FIRST checked input element in that DIV, which is always the one with the 'first' value after it is checked.
You should just get the value of the item which was clicked:
score = $(e.target||e.srcElement).val();
This can be rewritten as
score = $(this).val();
Here's a working example: http://jsfiddle.net/RPSwD/10/
See new fiddle.
The problem is this line:
score = obj.find('input:checked').val();
Change it to:
score = $(this).val();
The reason for this is that you're looking for the selected item in the div but on the first click, the item has yet to become selected. Given that the event is targeted at the radio button, you can assume that radio is the selected one.
Note also that you don't need to use e.target||e.srcElement. jQuery takes care of this for you. Use $(this) instead.
Additionally, you need to set a name on the radio buttons to stop both from becoming selected. Alternatively, if having both selected is desired behaviour, use check boxes instead.
You don't need to use any of the event properties:
var score = $(this).val(); // in your '.x' click handler
$('.y').click(function(e) {
$(this).prev('.x').click();
});
just wrap your radio button inside label tag like this
<label for="radio1">
<input type=radio class="x" id="radio1" value="First"/>
<span class="y">aaaa</span>
</label>
No need for extra jquery or javascript
check the demo here

Categories

Resources