AngularJS - uncheck radio button - javascript

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;
}

Related

How do i uncheck radio button in one click

I have the code to uncheck radio button, but the problem is, its not happening in one click when the radio button is checked, I am fetching the value of radio button as checked from mysql, so the default value of radio button is checked and when I click on the radio button the value should uncheck upon single click but my code is making it happen on double click. How do I make it happen with single click?
var check;
$('input[type="radio"]').hover(function() {
check = $(this).is(':checked');
});
var checkedradio;
function docheck(thisradio) {
if (checkedradio == thisradio) {
thisradio.checked = false;
checkedradio = null;
}
else {checkedradio = thisradio;}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="radio" name="check" value="check" onClick="javascript:docheck(this);" checked="checked"/>
Radios by design are meant to be used in a group (https://html.spec.whatwg.org/#radio-button-state-(type=radio)) - a group of 2 or more radios should form a group to allow the user to pick a value from the selection in that group. By design the radio group behaviour is this - once a selection is made (either by the user or programatically), that choice sticks, and there is no way to undo it, other than choose another radio option from the group. You'll see in your example, that without the JavaScript bit, if you by default uncheck the radio, then check it manually, you won't be able to uncheck it again. This is how it's supposed to work.
The rule of thumb should be that solving a problem on the backend should not come at the expense of the front-end, as it negatively impacts the user-experience, and will cause problems to the user. If you for any reason HAVE TO stick with such a bad UX solution, here is a way to hack your radio to act like a checkbox, but it is seriously not advised, and you should change your backend to use checkboxes instead.
Here is the radio hack (and a native checkbox input that should be used instead):
var myRadio = $('input[type="radio"]:checked');
myRadio.on('click', function() {
if (myRadio.attr('checked')) {
myRadio.removeAttr('checked');
myRadio.prop('checked', false);
} else {
myRadio.attr('checked', 'checked');
myRadio.prop('checked', true);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<b>This works, but it's bad UX, so avoid!</b><br>
<input type="radio" name="check" value="check" checked />
<hr>
<b>Use this instead!</b>
<br>
<input type="checkbox" name="real-check" value="real-check" checked />
You'll see that the jQuery selector is deliberately set to only pick the "checked" radio, so the JavaScript solution only takes over the native behaviour if the radio is checked by default. As soon as the radio is not checked by default, you'll see how the browser forces your selection once it's checked manually - this is a tell tale sign that you're trying to deviate from the expected behaviour.
You'll also see that the checkbox natively works - without the need for JavaScript or jQuery.
RobertP raised an interesting point about the user experience, or in IT-talk: "UX". In some cases it is mandatory that a single option needs to be clicked. This is exactly what radio buttons were made for. However, I have come across cases, where a "none" selection should also be offered. For these cases you could simply supply an extra radio button with the option "none" OR you could make the radio buttons "unselectable" again. This seems to go against the intended radio button behaviour. However, as it is possible to start out with no radio buttons being selected, why should it not be possible to return to this state after, maybe, the user had clicked on an item prematurely?
So, with these considerations in mind I went ahead and put together a way of doing what OP had in mind. I extended the example a little bit by including further radio button options:
$.fn.RBuncheckable=function(){ // simple jQuery plugin
const rb=this.filter('input[type=radio]'); // apply only on radio buttons ...
rb.each(function(){this.dataset.flag=$(this).is(':checked')?1:''})
.on('click',function(){
if (this.dataset.flag) $(this).prop('checked',false) // uncheck current
// mark whole group (characterised by same name) as unchecked:
else rb.filter('[name='+this.name+']').each(function(){this.dataset.flag=''});
this.dataset.flag=this.dataset.flag?'':1; // invert flag for current
});
return this;
}
$('input').RBuncheckable(); // apply it to all radio buttons on this page ...
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<h4>Two groups of radio buttons with "uncheck" option:</h4>
<input type="text" value="This input field is unaffected">
<p>group one:</p>
<label><input type="radio" name="check" value="a" checked /> Option A</label><br>
<label><input type="radio" name="check" value="b"/> Option B</label><br>
<label><input type="radio" name="check" value="c"/> Option C</label>
<p>group two:</p>
<label><input type="radio" name="second" value="d"/> Option D</label><br>
<label><input type="radio" name="second" value="e"/> Option E</label><br>
<label><input type="radio" name="second" value="f" checked/> Option F</label>
In the .each() loop I collect the initially checked state for all selected radio buttons. I store the individual checked state in a data attribute "flag" for each radio button.
The click event handler function then picks up this data flag and decides whether to step into action by either removing the checked state from the current element or simply resetting the flag data-attributes for the whole group (characterised by having the same name as the currently clicked one). In a last operation it then inverts the flag state for the current element again. As all data attributes are stored as strings, the values 1 and "" are "truthy" and "falsy" values that can be directly tested.
This results in exactly the behaviour you were looking for. I hope ;-)
By having the functionality packaged in a little jQuery plugin it can now be applied to any jQuery object directly.

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.

ko binding for checkbox: change 'checked' attr from code not change the observable field

I have checkbox at html that is binding to observable-field (field of breeze entity).
<input id="chk1" type="checkbox" data-bind="checked: data().isBirthday"/>
The binding works well from the tow sides:
When I write at code:
data().isBirthday(true);
the checkbox become checked.
and when I write at code
data().isBirthday(false);
the checkbox become unchecked.
And when I choose the checkbox by clicking with mouse - the observable field gets value of true. (Or when I unchecked by mouse - it gets value of false).
sometime, I need to change the checked attribute of the checkbox by code, specifically by retrive checkbox with jquery.
(I cannot do it by the observable field becouse of any reasons).
I do:
var control = $('#chk1')[0];
control.checked = false;
but this not change the value of the binded observable-field. It continue holding true value.
I tried to triiger the change event:
$(control).change()
It didn't help.
So, what should I do?
Here is an example:
https://jsfiddle.net/kevinvanlierde/72972fwt/4/
Can we see the html code?
Try $('#chk1').prop("checked", false);

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

Adding total of checked Radio Buttons

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;
}
}

Categories

Resources