Can't Limit Number of Checked Checkboxes - javascript

Not sure why the script doesn't work. Want it to uncheck one box when you try to select more than two. For example if you select CHEAP and FAST and then try and select GOOD, FAST is then unchecked.
document.querySelector('body').className = 'has-js';
var checked = [];
[].forEach.call(document.querySelectorAll('input[type="checkbox"]'), function (checkbox) {
checkbox.addEventListener('change', function (e) {
ga('send', 'event', 'checkbox', 'trigger');
if (checkbox.checked && checked.length === 2) {
var uncheckTarget = checked[Math.floor(Math.random() * checked.length)];
uncheckTarget.checked = false;
}
checked = document.querySelectorAll('input[type="checkbox"]:checked');
});
});
<div class="container">
<input type="checkbox" id="fast">
<label class="red" for="fast">FAST</label>
<input type="checkbox" id="good">
<label class="green" for="good">GOOD</label>
<input type="checkbox" id="cheap">
<label class="blue" for="cheap">CHEAP</label>
</div>

Your solution seems to be overly complicated. Also, you should use the click event instead of the change event for your callback because by the time change occurs, the checkmark is already present in the checkbox, so now you'd have to remove it. With click, you can just cancel the event, which occurs prior to the checkmark going into the checkbox.
var boxes = Array.prototype.slice.call(document.querySelectorAll('input[type="checkbox"]'));
boxes.forEach(function(chk) {
chk.addEventListener('click', function (e) {
if (document.querySelectorAll("input[type=checkbox]:checked").length > 2) {
e.preventDefault();
alert("You already have 2 checkboxes checked. Uncheck one and try again!");
}
});
});
<div class="container">
<input type="checkbox" id="fast"><label class="red" for="fast">FAST</label>
<input type="checkbox" id="good"><label class="green" for="good">GOOD</label>
<input type="checkbox" id="cheap"><label class="blue" for="cheap">CHEAP</label>
</div>

Related

How to Make an Element Appear and Disappear via Radio Button [duplicate]

I'm looking for a generalized solution for this.
Consider 2 radio type inputs with the same name. When submitted, the one that is checked determines the value that gets sent with the form:
<input type="radio" name="myRadios" onchange="handleChange1();" value="1" />
<input type="radio" name="myRadios" onchange="handleChange2();" value="2" />
The change event does not fire when a radio button is de-selected. So if the radio with value="1" is already selected and the user selects the second, handleChange1() does not run. This presents a problem (for me anyway) in that there is no event where I can catch this de-selection.
What I would like is a workaround for the onChange event for the checkbox group value or alternatively, an onCheck event that detects not only when a radio button is checked but also when it is unchecked.
I'm sure some of you have run into this problem before. What are some workarounds (or ideally what is the right way to handle this)? I just want to catch the change event, access the previously checked radio as well as the newly checked radio.
P.S.
onClick seems like a better (cross-browser) event to indicate when a radio button is checked but it still does not solve the unchecked problem.
I suppose it makes sense why onChange for a checkbox type does work in a case like this since it changes the value that it submits when you check or un-check it. I wish the radio buttons behaved more like a SELECT element's onChange but what can you do...
var rad = document.myForm.myRadios;
var prev = null;
for (var i = 0; i < rad.length; i++) {
rad[i].addEventListener('change', function() {
(prev) ? console.log(prev.value): null;
if (this !== prev) {
prev = this;
}
console.log(this.value)
});
}
<form name="myForm">
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
</form>
Here's a JSFiddle demo: https://jsfiddle.net/crp6em1z/
I would make two changes:
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
Use the onclick handler instead of onchange - you're changing the "checked state" of the radio input, not the value, so there's not a change event happening.
Use a single function, and pass this as a parameter, that will make it easy to check which value is currently selected.
ETA: Along with your handleClick() function, you can track the original / old value of the radio in a page-scoped variable. That is:
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
var currentValue = 0;
function handleClick(myRadio) {
alert('Old value: ' + currentValue);
alert('New value: ' + myRadio.value);
currentValue = myRadio.value;
}
<input type="radio" name="myRadios" onclick="handleClick(this);" value="1" />
<input type="radio" name="myRadios" onclick="handleClick(this);" value="2" />
As you can see from this example: http://jsfiddle.net/UTwGS/
HTML:
<label><input type="radio" value="1" name="my-radio">Radio One</label>
<label><input type="radio" value="2" name="my-radio">Radio One</label>
jQuery:
$('input[type="radio"]').on('click change', function(e) {
console.log(e.type);
});
both the click and change events are fired when selecting a radio button option (at least in some browsers).
I should also point out that in my example the click event is still fired when you use tab and the keyboard to select an option.
So, my point is that even though the change event is fired is some browsers, the click event should supply the coverage you need.
You can add the following JS script
<script>
function myfunction(event) {
alert('Checked radio with ID = ' + event.target.id);
}
document.querySelectorAll("input[name='myRadios']").forEach((input) => {
input.addEventListener('change', myfunction);
});
</script>
What about using the change event of Jquery?
$(function() {
$('input:radio[name="myRadios"]').change(function() {
if ($(this).val() == '1') {
alert("You selected the first option and deselected the second one");
} else {
alert("You selected the second option and deselected the first one");
}
});
});
jsfiddle: http://jsfiddle.net/f8233x20/
Easiest and power full way
read only radio inputs using getAttribute
document.addEventListener('input',(e)=>{
if(e.target.getAttribute('name')=="myRadios")
console.log(e.target.value)
})
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/
HTML
<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5
JS
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
//using radio elements previousCheckedRadio and currentCheckedRadio
//storing radio element for using in future 'change' event handler
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
JS EXAMPLE CODE
var changeHandler = (function initChangeHandler() {
var previousCheckedRadio = null;
function logInfo(info) {
if (!console || !console.log) return;
console.log(info);
}
function logPrevious(element) {
if (!element) return;
var message = element.value + ' was unchecked';
logInfo(message);
}
function logCurrent(element) {
if (!element) return;
var message = element.value + ' is checked';
logInfo(message);
}
var result = function (event) {
var currentCheckedRadio = event.target;
var name = currentCheckedRadio.name;
if (name !== 'myRadios') return;
logPrevious(previousCheckedRadio);
logCurrent(currentCheckedRadio);
previousCheckedRadio = currentCheckedRadio;
};
return result;
})();
document.addEventListener('change', changeHandler, false);
I don't think there is any way other then storing the previous state.
Here is the solution with jQuery
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
var lastSelected;
$(function () {
//if you have any radio selected by default
lastSelected = $('[name="myRadios"]:checked').val();
});
$(document).on('click', '[name="myRadios"]', function () {
if (lastSelected != $(this).val() && typeof lastSelected != "undefined") {
alert("radio box with value " + $('[name="myRadios"][value="' + lastSelected + '"]').val() + " was deselected");
}
lastSelected = $(this).val();
});
</script>
<input type="radio" name="myRadios" value="1" />
<input type="radio" name="myRadios" value="2" />
<input type="radio" name="myRadios" value="3" />
<input type="radio" name="myRadios" value="4" />
<input type="radio" name="myRadios" value="5" />
After thinking about it a bit more, I decided to get rid of the variable and add/remove class. Here is what I got: http://jsfiddle.net/BeQh3/2/
I realize this is an old issue, but this snippet of code works for me. Perhaps someone in the future will find it useful:
<h2>Testing radio functionality</h2>
<script type="text/javascript">var radioArray=[null];</script>
<input name="juju" value="button1" type="radio" onclick="radioChange('juju','button1',radioArray);" />Button 1
<input name="juju" value="button2" type="radio" onclick="radioChange('juju','button2',radioArray);" />Button 2
<input name="juju" value="button3" type="radio" onclick="radioChange('juju','button3',radioArray);" />Button 3
<br />
<script type="text/javascript">
function radioChange(radioSet,radioButton,radioArray)
{
//if(radioArray instanceof Array) {alert('Array Passed');}
var oldButton=radioArray[0];
if(radioArray[0] == null)
{
alert('Old button was not defined');
radioArray[0]=radioButton;
}
else
{
alert('Old button was set to ' + oldButton);
radioArray[0]=radioButton;
}
alert('New button is set to ' + radioArray[0]);
}
</script>
As you can see here:
http://www.w3schools.com/jsref/event_onchange.asp
The onchange attribute is not supported for radio buttons.
The first SO question linked by you gives you the answer: Use the onclick event instead and check the radio button state inside of the function it triggers.
Yes there is no change event for currently selected radio button. But problem is when each radio button is taken as a separate element. Instead a radio group should be considered a single element like select. So change event is triggered for that group. If it is a select element we never worry about each option in it, but take only the selected option. We store the current value in a variable which will become the previous value, when a new option is selected. Similarly you have to use a separate variable for storing value of checked radio button.
If you want to identify the previous radio button, you have to loop on mousedown event.
var radios = document.getElementsByName("myRadios");
var val;
for(var i = 0; i < radios.length; i++){
if(radios[i].checked){
val = radios[i].value;
}
}
see this : http://jsfiddle.net/diode/tywx6/2/
This is just off the top of my head, but you could do an onClick event for each radio button, give them all different IDs, and then make a for loop in the event to go through each radio button in the group and find which is was checked by looking at the 'checked' attribute. The id of the checked one would be stored as a variable, but you might want to use a temp variable first to make sure that the value of that variable changed, since the click event would fire whether or not a new radio button was checked.
<input type="radio" name="brd" onclick="javascript:brd();" value="IN">
<input type="radio" name="brd" onclick="javascript:brd();" value="EX">`
<script type="text/javascript">
function brd() {alert($('[name="brd"]:checked').val());}
</script>
If you want to avoid inline script, you can simply listen for a click event on the radio. This can be achieved with plain Javascript by listening to a click event on
for (var radioCounter = 0 ; radioCounter < document.getElementsByName('myRadios').length; radioCounter++) {
document.getElementsByName('myRadios')[radioCounter].onclick = function() {
//VALUE OF THE CLICKED RADIO ELEMENT
console.log('this : ',this.value);
}
}
this works for me
<input ID="TIPO_INST-0" Name="TIPO_INST" Type="Radio" value="UNAM" onchange="convenio_unam();">UNAM
<script type="text/javascript">
function convenio_unam(){
if(this.document.getElementById('TIPO_INST-0').checked){
$("#convenio_unam").hide();
}else{
$("#convenio_unam").show();
}
}
</script>
This is the easiest and most efficient function to use just add as many buttons as you want to the checked = false and make the onclick event of each radio buttoncall this function. Designate a unique number to each radio
button
function AdjustRadios(which)
{
if(which==1)
document.getElementById("rdpPrivate").checked=false;
else if(which==2)
document.getElementById("rdbPublic").checked=false;
}
For some reason, the best answer does not works for me.
I improved best answer by use
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
Original best answer use:
var rad = document.myForm.myRadios;
The others keep the same, finally it works for me.
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
html is:
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' disabled/>
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' disabled/>
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
console.log('overlayType_radio', overlayType_radio)
var prev = null;
for (var i = 0; i < overlayType_radio.length; i++) {
overlayType_radio[i].addEventListener('change', function() {
(prev) ? console.log('radio prev value',prev.value): null;
if (this !== prev) {
prev = this;
}
console.log('radio now value ', this.value)
});
}
<div id='overlay-div'>
<fieldset>
<legend> Overlay Type </legend>
<p>
<label>
<input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
<span>Image</span>
</label>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' />
<span> Tiled Image</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio' />
<span> Coordinated Tile</span>
</p>
<p>
<label>
<input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
<span> None </span>
</p>
</fieldset>
</div>
jsfiddle click here
https://jsfiddle.net/hoogw/jetmkn02/1/
Tl;dr
'focusout' is dispatched before the 'change' event - example:
const radioName = 'radio';
// Add radios
document.body.innerHTML = `
<style>
input + label {
margin-left: 1rem;
}
</style>
<form action="#" name="example-form">
<fieldset>
${Array(5).fill(null, 0, 5).map((_, i) => {
const offsetId = i + 1;
const id = `radio-${offsetId}`;
return `<label for="${id}">Radio ${offsetId}</label>
<input type="radio" name="${radioName}" id="${id}" value="${offsetId}" />`;
}).join('\n')}
</fieldset>
</form>
`;
const {log} = console,
form = document.forms['example-form'];
form.addEventListener('submit', e => e.preventDefault());
form.addEventListener('change', e => {
const {target} = e;
if (target.matches(`[type="radio"][name="${radioName}"]`)) {
log(`[${e.type}]: "${target.id}" selected; Value: ${target.value}`);
}
});
form.addEventListener('focusout', e => {
const {target} = e,
soonToBePrevValue = target && target.form ?
target.form.elements[radioName].value : null;
if (!target.matches(`[type="radio"][name="${radioName}"]`) || !soonToBePrevValue) {
return;
}
// value, for '[name="radio"]', contained in form, will change after 'focusout' event
// has completed it's bubbling stage.
log(`[${e.type}]: previously selected radio value: ` +
`${soonToBePrevValue}`);
// log("Soon to be \"previous\" radio: ", target);
});
jsfiddle
<script>
function radioClick(radio){
alert()
}
</script>
<label>Cash on delivery</label>
<input type="radio" onclick="radioClick('A')" name="payment_method" class="form-group">
<br>
<label>Debit/Credit card, GPay, Paytm etc..</label>
<input type="radio" onclick="radioClick('B')" name="payment_method" class="form-group">

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

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.

Add required to input of hidden div when radio is checked

What I'm trying to do is to set hidden div with inputs depended on checked radio input.
This is the logic:
If the first radio is checked the first div is shown, there I want to add hidden inputs with some values...
If the second radio is checked I want the input to be added with required..
And, it shouldn't be required if the 2nd radio isn't checked...
I've tried a few things over some time and got some effects but can't get it work as I want, Here is the code that i'm currently trying to work with, sorry but it's messed up and fails...
So Any help will be much appreciated...
/*
// this code is working but I messed the HTML while trying to get it work with the other code below...
$(document).ready(function() {
$("div.hiddendiv").hide();
check();
$("input[name$='name02']").change(check);
function check() {
var test = $("input[name$='name02']:checked").val();
$("div.hiddendiv").hide();
$("#" + test).show();
}
}
*/
// The code i'm trying to work with...
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
checkbox.change(function() {
if (checkbox.is(':checked')) {
hidden.show();
//add required
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" id="closed" value="01"> Closed
<input type="radio" id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" type="text" value="">
</div>
Here is the JSFiddle,
try this code
give same name of radio button so it will work as a group and
also set id of input tag as name02 so its use as a #name02 in jquery
so it will work
$(function() {
var radio = $("#closed");
var hidden = $("#hide");
hidden.hide();
$(this).click(function() {
if ($('#closed').is(':checked')) {
hidden.show();
$('#name02').prop('required', true);
} else {
hidden.hide();
//clear when hidden checked
$("#name02").val("");
//remove required
$('#name02').prop('required', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="radio" name='btn' id="closed" value="01"> Closed
<input type="radio" name='btn' id="open" value="02"> Open
<div name="01" class="hiddendiv">
<input name="name01" type="hidden" value="code">
</div>
<div name="02" id="hide" class="hiddendiv">
<input name="name02" id="name02" type="text" value="">
</div>
Part of your problem is that you need to set the name attribute of your radio buttons to be the same value, otherwise the HTML won't know that they belong to the same group.
I've updated the JSfiddle here
https://jsfiddle.net/hba4d83k/2/
What i have done is add a change event handler to your the radio group and then did some conditional logic to show/hide the relevant inputs.

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.

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