Use checkbox to clear/update radio buttons in html/angularjs - javascript

My form has a checkbox followed by several radio buttons.Basically, the design calls for a user to be able to use a checkbox to clear a set of radio buttons (or set a default value). If the user should select a radio button then the checkbox will also be set.
Overall most of the requirements are met by the code below, however there is one condition when it doesn't work:
User Selects Checkbox. (Check appears in checkbox)
User Selects Radio button. (Radio button is selected)
User Selects Checkbox Again. (Check disappears from checkbox and radio button deselects)
User Selects Radio button. (Check appears in checkbox and radio button selects)
User deselects Checkbox. (Check disappears but the value isn't updated so the radio button does not deselect)
What is happening? How can this be written to get the behavior my user wants?
Thanks,
Matt
Here is the code:
var myAngular=angular.module('myApp',[]);
myAngular.controller('myController',function($scope){
$scope.title="Angular Radio Buttons";
$scope.selectedValue='i10';
$scope.numStatus = 0;
$scope.numStatusChanged = function () {
console.log('numStatusChanged:')
if ($scope.numStatus === 0) {
$scope.numStatus = 3;
console.log('From 0 to 3.');
} else {
$scope.numStatus = 0;
console.log('From ' + $scope.numStatus + ' to 0.' )
}
};
$scope.$watch('numStatus', function(newValue,oldValue,scope){
console.log('newVal:' + newValue + ' oldValue:' + oldValue);
});
$scope.$watch('aBool', function(newValue,oldValue,scope){
console.log('aBoolNew:' + newValue + ' aBoolOld:' + oldValue);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='myApp'>
<div ng-controller='myController'>
<p>Selected Value: {{numStatus}}</p>
<div class="checkBoxGroup">
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-checked="numStatus !== 0" ng-change="numStatusChanged()">
<label for="isCheckbox">A Value Is Selected</label>
<div class="radio-button-vertical">
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="1" name="numStatus" /> One</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="2" name="numStatus" /> Two</label>
</div>
<div class="radio">
<label class="radio-inline"><input type="radio" ng-model="numStatus" data-ng-value="3" name="numStatus" /> Three</label>
</div>
</div>
</div>
</div>
</div>

You are using ngChecked and ngModel together, I would expect that your issue is that those two properties are conflicting with each other since they represent similar bindings (other SO post explaining this).
Just rewrite the checkbox to be:
<input type="checkbox" id="isCheckbox" ng-model="aBool" value="" ng-change="numStatusChanged()">
and then do the numStatus !== 0 check in the numStatusChanged() method and use the result to set aBool.

Related

Javascript to enable/disable radio buttons when text field is cleared or chars are present

I'm working on a little script that will disable a form field if certain radio button are ticked or if the input filed has characters to disable the radio buttons
So what I'm wanting my code to do is when the User enters the text field and adds at least one character of any type to disable the radio buttons and if that field is cleared to re-enable the radio buttons
For some reason when I'm doing either or, my "Enabled" alert keeps showing and the radio buttons aren't being disabled
to get the alert to pop, need to click outside of the input field, I would like this to be a mouseout if possible but I can work on that later
If the value is entered within the form directly, the radio buttons are disabled but I can't get them enabled once the filed is cleared
Steps:
Enter text in text field, if value isn't set in the form. Radio buttons stay disabled
Enter Value within the form, the text buttons stay disabled when the text field is cleared
Working Parts:
If radio btn "Yes" is ticked display "test" string and disable text field
If Radio btn "No" is ticked then enable text field
jQuery version in use: 1.9
Below is my JavaScript and below that is the HTML
Script:
$(function() {
var tlHeader = 'Test';
var f2 = $('#field_2').val();
// This function controls inpput box toggling on/off radio buttons
$( '#field_2' ).change(function() {
if(f2.length != 0) {
alert( "Disabled" )
$("input[name=toggle]").prop('disabled', true)
} else if(f2.length == 0) {
alert( "Enabled" )
$("input[name=toggle]").removeProp('disabled')
};
});
window.invalidate_input = function() {
// This function controls radio btn actions
if ($('input[name=toggle]:checked').val() == "Yes") {
$('#field_2').attr('disabled', 'disabled'),
$('#thgtLdr').html( tlHeader );
$('#thgtLdr').not("No").show();
} else if ($('input[name=toggle]:checked').val() == "No") {
$('#field_2').removeAttr('disabled'),
$('#thgtLdr').not("Yes").hide();
}
};
$("input[name=toggle]").change(invalidate_input);
invalidate_input();
});
</script>
HTML:
<body>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div> <!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes"/>Yes
<input type='radio' name='toggle' value='No' id="tglno"/>No
</div>
<div id="thgtLdr">
</div>
</div>
</body>
Your use case isnt entirely clear but I'll show you how to achieve the basic goal.
First, I would avoid the mouse events and use keyup with a timer so that my function is only called when the user stops typing and not after each typed letter. Then it's just a mater of checking the text and acting to enable or disable the elements. Here is an example:
var keyupDelay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
$('#field_2').keyup(function() {
var $this=$(this);
keyupDelay(function(){
var val=$this.val();
console.log(val);
if(val=='') $('#tglyes, #tglno').prop('disabled',true);
else $('#tglyes, #tglno').prop('disabled',false);
}, 400 ); // triggered after user stops typing for .4 seconds, adjust value as needed
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class='textbox' value="" />
</div>
<!-- End input field -->
<div class="radioGroup">
<label>Test Page:</label>
<input type='radio' name='toggle' value='Yes' id="tglyes" disabled="true"/>Yes
<input type='radio' name='toggle' value='No' id="tglno" disabled="true"/>No
</div>
<div id="thgtLdr">
</div>
</div>
Try this
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click','.choice',function(){
if($(this).val() == 'yes')
{
$('.textfield').prop('disabled',true);
$('#string').html('Test Welcome');
}
else
{
$('.textfield').prop('disabled',false);
$('#string').html('');
}
});
$(document).on('keyup','.textfield',function(){
if($(this).val().length > 0)
{
$('.choice').each(function()
{
if($(this).is(':checked'))
{
$(this).attr('checked',false);
}
$(this).prop('disabled',true);
});
}
else
{
$('.choice').prop('disabled',false);
}
});
});
</script>
<body>
<form>
<input type="text" class="textfield" placeholder="enter text"/>
Yes<input type="radio" name="choice" class="choice" value="yes" />
No<input type="radio" name="choice" class="choice" value="no" />
<p id="string" ></p>
</form>
</body>
You can simplify your code in many ways.
The keyup event will be triggered every time the user releases a key on the text field. Inside the callback, you can get the value of the text field with this.value. From experience, it is best to use .prop() method when toggling certain input-related attributes like disabled and checked. You can enable/disable these attributes using booleans.
// cache the elements to avoid having retrieve the same elements many times
var $textbox = $('#field_2'),
$radios = $('input[name=toggle]'),
$div = $('#thgtLdr');
// everytime user presses a key...
$textbox.on('keyup', function() {
// check if a value was entered or not
// if so, disabled the radio buttons; otherwise enable the radio buttons
$radios.prop('disabled', this.value);
});
// when radio buttons change...
$radios.on('change', function () {
// check if value is Yes or No
if (this.value === 'Yes') {
$textbox.prop('disabled', true);
$div.text(this.value);
} else {
$textbox.prop('disabled', false);
$div.empty();
}
});
<div id=rdTest>
<div class="inputField">
<label>Focal Image:</label>
<input name="FocalImage" type="text" id="field_2" class="textbox" value="">
</div>
<div class="radioGroup">
<label>Test Page:</label>
<input type="radio" name="toggle" value="Yes" id="tglyes">Yes
<input type="radio" name="toggle" value='No' id="tglno">No
</div>
<div id="thgtLdr"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script> // place code here </script>
Also, get into the habit of caching your jQuery objects.

How to get the value of a selected radio button before the change?

I have multiple radio button sharing the same name. One of them has a hidden div next to It.
When the correct radio button is selected, I want to show/hide the div that is next it to it "if one is there"
Here is an example
Radio 1
Radio 2
Radio 3
Radio 4
Next to Radio 2 there is a hidden div. I want to show it when Radio 2 is selected. Then when Radio 4 is selected, I want to hide the Radio 2 div
Here is what I have done
$(function(){
function getGroupElement(value)
{
return '#group_' + value.replace(':', '_');
}
var previous;
$("input[type='radio']").click(function(e) {
// Store the current value on focus and on change
previous = $(this).val();
console.log('Current:' + previous);
}).change(function(e) {
var previousGroupId = getGroupElement(previous);
var newGroupName = $(this).data('show-group');
//Hide the previous Group
$(previousGroupId).hide();
if ( ! newGroupName){
return;
}
$(newGroupName).show();
});
});
My code above is not working because previous is set to the next selected item.
How can I hide/show the correct box?
If needed here is my HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<fieldset class="survey-control-fieldset">
<div class="survey-control-title">
Select a store
</div>
<div class="radio">
<label for="item_529"><input checked id="item_529" name=
"control_111" type="radio" value="112:529"> None</label>
</div>
<div class="radio">
<label for="item_530"><input id="item_530" name="control_111" type=
"radio" value="112:530"> Don't Know/No Answer</label>
</div>
<div class="radio">
<label for="item_532"><input data-show-group="group_112_532" id=
"item_532" name="control_111" type="radio" value="112:532">
Other</label>
<div id="group_112_532" style="display: none;">
<div class="form-group">
<label for="control_113">Specify Other Store Name</label>
<input class="form-control" id="control_113" name=
"control_113" placeholder="" type="text" value="">
</div>
</div>
</div>
<div class="radio">
<label for="item_531"><input id="item_531" name="control_111" type=
"radio" value="112:531"> Refused</label>
</div>
</fieldset>
</body>
</html>
Hide all the DIVs that are next to radios, then show the one next to the selected radio.
$(":radio").next("div").hide();
$(this).next("div").show();
If you give each of the hidden div's the same class name, you can just hide them all before you show the new one:
$('.hidden-divs').not(newGroupName).hide();
$(newGroupName).show();

Allow only one radio button to be selected from multiple groups of checkboxes

I have a number of account items.
I am displaying these in a list doing something like
<md-list-item ng-repeat="item in items">
and for every such item i display three radio buttons in a group, holding values like
admin
user
moderator
Right now a user can select a value for each group of radio buttons, but what I want to do is have only one admin.
So if an admin value is selected the I should block all other admin radio buttons.
How can this be done?
Have a ng-change method that stores the admin item in a scope property to keep track of which item has admin selected:
$scope.radioChanged = function (item) {
if (item.selectedValue == "admin") {
$scope.admin = item;
}
else if (item == $scope.admin) {
$scope.admin = undefined;
}
};
Then use ng-disabled on the admin radio button that will disable the radio button if an admin has been selected and the admin is not the current item.
<div ng-repeat="item in items">
<label><input type="radio" name="{{item.id}}" value="admin" ng-model="item.selectedValue" ng-change="radioChanged(item)" ng-disabled="admin && item != admin"/>admin</label>
<label><input type="radio" name="{{item.id}}" value="user" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>user</label>
<label><input type="radio" name="{{item.id}}" value="moderator" ng-model="item.selectedValue" ng-change="radioChanged(item)"/>moderator</label>
</div>
Plunkr
I would create a variable, maybe adminExists, that is set to true when you select 'Admin' on any of the radio buttons. You could then have all the "Admin" radio buttons become disabled if(adminExists && !isSelected), where isSelected is true if that radio button is the admin button that was selected.
The code below checks the value of the selected radio button against the value of other radio buttons to see if they match up (in this case if the value is "admin"). It then deselects all the radio input elements with that value and then checks the element that was initially clicked or selected to set it to active. You can change the function to use a data attribute instead of the value if you'd prefer as well.
$(".group input[type=radio]").bind("click change keydown focus", function () {
var el = $(this);
var val = el.val();
if (el.prop("checked", true) && val == "admin") {
$(".group input[type=radio]").each(function () {
if ($(this).val() == "admin") $(this).prop("checked", false);
});
el.prop("checked", true);
}
});
.choice {
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<div class="group">
<div class="choice">
<input type="radio" name="group[0][]" value="admin" />
<label>Admin</label>
</div>
<div class="choice">
<input type="radio" name="group[0][]" value="user" />
<label>User</label>
</div>
<div class="choice">
<input type="radio" name="group[0][]" value="moderator" />
<label>Moderator</label>
</div>
</div>
<div class="group">
<div class="choice">
<input type="radio" name="group[1][]" value="admin" />
<label>Admin</label>
</div>
<div class="choice">
<input type="radio" name="group[1][]" value="user" />
<label>User</label>
</div>
<div class="choice">
<input type="radio" name="group[1][]" value="moderator" />
<label>Moderator</label>
</div>
</div>
</form>

Jquery get value of text box next to a radio button

I am creating a form with multiple radio buttons and text boxes.
Each Text box is next to radio button like below:
<div class="form-group">
<div class="radio">
<label>
<input type="radio" name="correct_answer_id">
Correct
</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required>
</div>
</div>
There are several radio button and text box pair like above in the form.
On click of the radio button, i want to get whatever has been written in the corresponding text box
i am trying to use Jquery's next() function like below:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).next('input[type="text"]').val());
}
});
But my log shows undefined. What i am doing wrong?
Try this : find parent div of radio and do next().next() to get input box div and then find input box to get value.
NOTE - You need not to check if ($(this).is(':checked')) as when you click on radio button it will get checked always.
$('input[type="radio"]').click(function(){
var value = $(this).closest('.radio').next().next('.col-sm-10').find('input[type=text]').val();
console.log(value );
});
use below code using parents(); see working fiddle
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parents('div.radio').next().next('div.col-sm-10').find('input[type="text"]').val());
}
});
You should put the value that you want submitted in the value attribute of your input elements.
e.g. <input type="radio" name="correct_answer_id" value="correct">
Your click handler would change to:
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).val());
}
});
If there's some value that you don't want to place in the value attribute then it's still best to have a reference to the value in the input element instead of relying on a particular document layout.
Try this
$('input[type="radio"]').click(function(){
if ($(this).is(':checked'))
{
console.log($(this).parent().parent().siblings().find('input[type="text"]').val());
}
});
Working Demo
If you can change the html a little, here is a different approach http://jsfiddle.net/xa9cjLd9/1/
<div class="form-group">
<div class="radio">
<label data-for='answer[]'>
<input type="radio" name="correct_answer_id" />Correct</label>
</div>
<label for="answer" class="col-sm-2 control-label">Answer 2</label>
<div class="col-sm-10">
<input type="text" class="form-control" name="answer[]" placeholder="Answer" required />
</div>
</div>
$('input[type="radio"]').click(function () {
if ($(this).is(':checked')) {
var data = $(this).closest('label').attr('data-for');
console.log($('input[name=' + '"' + data + '"' + ']').val());
}
});
Just Define a data attribute to the label , which contains the name of the related input.

jQuery checking radio box status and showing an element

I'm trying to show a div of another set of radio boxes but only depending on which radio button is first selected.
If option option one is selected, I would like condition one div to show and if option two is selected I would like condition two div to show.
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
if ($("id=[option-one]").is(":checked")) {
$('#visible-condition-one').show("slow");
} else if ($("id=[option-two]").is(":checked")) {
$('#visible-condition-two').show("slow");
};
});
<div id="always-visible">
<label class="control-label">Would you like option 1 or option 2</label><br>
<label class="radio-label"><input type="radio" id="option-one" name="option-info"> Option 1</label>
<label class="radio-label"><input type="radio" id="option-two" name="option-info"> Option 2</label>
</div>
<div id="condition-one">
<label class="control-label">If you pick option 1, you see this div</label><br>
<label class="radio-label"><input type="radio" id="option-three" name="option-info-group-two"> Option 3</label>
<label class="radio-label"><input type="radio" id="option-four" name="option-info-group-two"> Option 4</label>
</div>
<div id="condition-two">
<label class="control-label">If you pick option 2, you see this div</label><br>
<label class="radio-label"><input type="radio" id="option-five" name="option-info-group-three"> Option 5</label>
<label class="radio-label"><input type="radio" id="option-six" name="option-info-group-three"> Option 6</label>
</div>
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
$("#option-one").on("change", function() {
if($(this).is(":checked")) {
$('#condition-one').show("slow");
}
});
$("#option-two").on("change", function() {
if($(this).is(":checked")) {
$('#condition-two').show("slow");
}
});
});
In your code, the action must be taken on user input, in this case, a radio box. You must attach a 'change' event to your radio boxes and when user changes status, the callback function is triggered.
How about the following:
//Cache our deciding radio buttons
var $radio = $('#always-visible :radio'),
//An array of the available radio/div identifiers
ids = ['one', 'two'];
//Bind an event to your deciding radio buttons
$radio.change(function(){
//That will loop through your radio buttons
$.each(ids, function(_, n){
//See if this one is checked
var checked = $('#option-' + n).prop('checked');
//If so, show the relevant block, otherwise hide it
$('#condition-' + n).toggle(checked);
});
//Trigger the event on page load
}).change();
JSFiddle
i just did something similar(working)
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#condition-one').hide();
$('#condition-two').hide();
$(".radio-label").on("change", function() {
if ($('.radio-label#1').is(':checked')) { // if the radiolabel of id=1 is checked
$('#condition-one').show("slow"); //show condition one
$('#condition-two').hide();
} else if ($(".radio-label#2").is(":checked")) {
$('#condition-two').show("slow");
$('#condition-one').hide("slow");
}
});
});
</script>
</head>
<body>
<input type="radio" class="radio-label" id="1" name="option-info"></input>
<input type="radio" class="radio-label" id="2" name="option-info"></input>
<div id="condition-one">
test1
</div>
<div id="condition-two">
test2
</div>
</body>

Categories