How to disable a radio button if the other one is selected? - javascript

I'm trying to disable a radio button if the other one is selected.
Next to the radio input is a text input in which if they choose the option, they would write the age depending on the selection of the radio (months or years).
Ideally, the text input would be disabled too. I have this code right now but it's not working:
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i><label data-error="wrong" data-success="right" style="padding-left: 5px">Age: </label>
<br />
<input type="radio" id="age_in_years" name="age_in_years" value="years">
<label for="age_in_years">Años:</label><input id="age_in_years"type="number" name="age_in_years" ng-model="age_in_years" class="form-control" style="margin-left: 5px;width: 70px;"/>
<input type="radio" id="age_in_months" name="age_in_months" value="months">
<label for="age_in_months">Months:</label><input id="age_in_months" type="number" name="age_in_months" value="age_in_months" ng-model="age_in_months" class="form-control" style="margin-left: 5px;width:70px;"/>
</div>
<script>
function selection() {
let x = document.getElementById("age_in_years");
let y = document.getElementById("age_in_months");
if (x.checked()) {
document.getElementById("age_in_months").disabled = true;
}
else if (y.checked()) {
document.getElementById("age_in_years").disabled = true;
}
}
</script>

I would refactor the HTML slightly and generate the radio buttons with the same name so that only 1 can ever be checked at a time. With that in place some simple javascript to determine the other inputs can be used to disable the number input.
label elements should not be used for arbitrary HTML - they are to be associated with input elements ( either using for=ID syntax or by wrapping the input element itself ) - hence some alterations to the markup.
document.addEventListener('change',e=>{
if( e.target.name=='age_unit' ){
let parent=e.target.parentNode;
let self=parent.querySelector(`input[type='number'][name='age[${e.target.value}]']`);
let other=parent.querySelector(`input[type='number']:not( [name='age[${e.target.value}]'] )`);
self.disabled=false;
other.disabled=true;
self.required=true;
other.required=false;
self.focus();
}
})
[type='number']{
width:70px;
}
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i>
<h2>Age:</h2>
<input type="radio" name="age_unit" value="years" />
<label>Años:
<input type="number" name="age[years]" ng-model="age_in_years" class="form-control" disabled />
</label>
<input type="radio" name="age_unit" value="months" />
<label>Months:
<input type="number" name="age[months]" ng-model="age_in_months" class="form-control" disabled />
</label>
</div>

A radio type is grouped by the name, so using the same name would already give the behavior you want, without needing any JavaScript.
<div class="md-form mb-3">
<i class="fas fa-paw prefix grey-text"></i>
<label data-error="wrong" data-success="right" style="padding-left: 5px">Age: </label>
<br>
<input type="radio" id="age_in_years" name="age" value="years">
<label for="age_in_years">Años:</label><input id="age_in_years"type="number" name="age_in_years" ng-model="age_in_years" class="form-control" style="margin-left: 5px;width: 70px;"/>
<input type="radio" id="age_in_months" name="age" value="months">
<label for="age_in_months">Months:</label>
<input id="age_in_months" type="number" name="age_in_months" value="age_in_months" ng-model="age_in_months" class="form-control" style="margin-left: 5px;width:70px;"/>
</div>
This would make sure that if one of radio elements is clicked or, once another one is clicked, the previous would be unchecked.
Because you have a value there, there's no reason to use different names, because the value already hints what kind of data has been submitted or is required.

Related

How to check multiple selectors to trigger an event?

New to jquery but I am working on a responsive calendar. Now I have a start date and an end date field. If the end date is populated, the reoccurrence check box shows as it removes it from the not-visible class.
How can I add a check on the start date also? I want the check box to show when both of the start and end fields are filled not just one.
$("#end_date").on("input", function (){
if($('#end_date').length >= 1) {
$("#reoccurrence").removeClass('not-visible');
} else {
$("#reoccurrence").addClass('not-visible');
}
});
.not-visible {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="start_date" class="form-control date-picker" name="start_date" required />
<label for="start_date">Start Date</label>
</div>
</div>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="end_date" class="form-control date-picker" name="end_date" required />
<label for="end_date">End Date</label>
</div>
</div>
<div class="form-check not-visible" id="reoccurrence" name="reoccurrence">
<input class="form-check-input" type="checkbox" id="is_reoccurring" name="is_reoccurring" value="1" />
<label class="form-check-label" for="is_reoccurring"> Reoccurrence? </label>
</div>
In this context, using length will tell you whether that input exists in the DOM (0 = doesn't exist, 1 = exists), but it won't evaluate the values of the inputs.
length
The number of elements in the jQuery object.
The number of elements currently matched.
Instead, I recommend using val() to verify that the values of both inputs are not empty strings.
In the demonstration below, I define each input and the "reoccurrence" element as variables. I use add() to combine the two inputs and bind the event handler to both. Alternatively, you could simply select both inputs: $("#start_date,#end_date"); see multiple selector.
Upon input, I define a boolean "oneEmpty" variable based on the values of both inputs. Then, I use toggleClass() to "add or remove one or more classes ... depending on ... the value of the state argument."
When either input is empty, the "oneEmpty" state is true and the "not-visible" class is toggled on. When both inputs are filled, the state is false and the class is toggled off.
var $start_date = $('#start_date');
var $end_date = $('#end_date');
var $reoccurrence = $("#reoccurrence");
$start_date.add($end_date).on("input", function() {
let oneEmpty = $start_date.val() == '' || $end_date.val() == '';
$reoccurrence.toggleClass('not-visible', oneEmpty);
});
.not-visible {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="start_date" class="form-control date-picker" name="start_date" required />
<label for="start_date">Start Date</label>
</div>
</div>
<div class="col">
<div class="md-form md-form-container-fix">
<input type="text" id="end_date" class="form-control date-picker" name="end_date" required />
<label for="end_date">End Date</label>
</div>
</div>
<div class="form-check not-visible" id="reoccurrence" name="reoccurrence">
<input class="form-check-input" type="checkbox" id="is_reoccurring" name="is_reoccurring" value="1" />
<label class="form-check-label" for="is_reoccurring"> Reoccurrence? </label>
</div>

Select radio button on text input

Is there option for radio button to be auto selected when visitor enter text in another input form? I have searched for it, but without success.
I have this form with 3 radio buttons, they allow users to choose size, last radio button is for custom size (width and height). Under last radio button there is text input to input custom height and width.
<form action="#" method="post">
<label for="original-size">Original
<input type="radio" id="original_size" name="size" value="original" checked="checked">
</label>
<label for="medium-size">Medium
<input type="radio" id="medium-size" name="size" value="medium">
</label>
<label for="custom-size">Custom
<input type="radio" id="custom-size" name="size" value="custom">
</label>
<input id="custom-width" type="number" name="custom-width" placeholder="Custom width">
<label for="custom-width">custom width</label>
and
<input id="custom-height" type="number" name="custom-height" placeholder="Custom height">
<label for="custom-height">custom height</label>
<br>
<button name="submit" type="submit">Submit</button>
</form>
How to select custom-size radio input if user click on custom-width or custom-height text input? Is there option without java script, if not, small code of java script would be fine (I am not using jQuery)?
Managed to dig up this, is this what you are looking for?
<form>
<p>Original: <input type="text"></p>
<p>Medium: <input type="text"></p>
<div id="customWrapper">
<p>Custom: <input type="radio" id="customSize"></p>
<p>Custom Width: <input type="text"></p>
<p>Custom Height: <input type="text"> </p>
</div>
</form>
const div = document.getElementById('customWrapper');
// When the custom width or custom height are clicked on
div.addEventListener('focus', (event) => {
document.getElementById('customSize').checked = true;
}, true);
// When clicked somewhere out of the form
div.addEventListener('blur', (event) => {
document.getElementById('customSize').checked = false;
}, true);
https://jsfiddle.net/mLvt9ubz/
It basically searches for any input inside the div, when it's event changes then something happens.
In this case the radio button with an ID get's the attribute selected.

Show / hide div on page load depending on radio button value - Jquery and Ruby on Rails Simple Form

Using Jquery with Ruby on Rails and the Simple Form Gem I can successfully show / hide a div on changing a radio button, however despite numerous attempts I can't get this to work on page load - divs are always showing, whether the radio button is true or false. Any help would be great thanks.
jQuery(document).ready(function() {
jQuery('[name="user[nurse_attributes][qualified]"]').on('change', function() {
if (jQuery(this).val() == 'true' ) {
jQuery('#denied-quote-one').hide();
} else {
jQuery('#denied-quote-one').show();
}
});
});
UPDATE - HTML OUTPUT OF RADIO BUTTONS:
<div class="form-group radio_buttons optional user_nurse_qualified">
<input type="hidden" name="user[nurse_attributes][qualified]" value="">
<span class="radio">
<label for="user_nurse_attributes_qualified_true">
<input class="radio_buttons optional" type="radio" value="true" checked="checked" name="user[nurse_attributes][qualified]" id="user_nurse_attributes_qualified_true">Yes
</label>
</span>
<span class="radio">
<label for="user_nurse_attributes_qualified_false">
<input class="radio_buttons optional" readonly="readonly" type="radio" value="false" name="user[nurse_attributes][qualified]" id="user_nurse_attributes_qualified_false">No
</label>
</span>
</div>
<div id="denied-quote-one" style="display: block;">
<p class="p-red">Unfortunately we cannot give you a quote if your answer to this question is no. You will not be able to move forward.
</p>
</div>
Your code above adds an event handler for the change event on the radio button. Aside from that, you need to check the value of the :checked radio button on page load, and show/hide based on that.
Note: To prevent flickering, give the element an initial style of display: none.
jQuery(document).ready(function() {
if ( jQuery('[name="user[nurse_attributes][qualified]"]:checked').val() !== 'true' ) {
jQuery('#denied-quote-one').show();
}
jQuery('[name="user[nurse_attributes][qualified]"]').on('change', function() {
if (jQuery(this).val() == 'true' ) {
jQuery('#denied-quote-one').hide();
} else {
jQuery('#denied-quote-one').show();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group radio_buttons optional user_nurse_qualified">
<input type="hidden" name="user[nurse_attributes][qualified]" value="">
<span class="radio">
<label for="user_nurse_attributes_qualified_true">
<input class="radio_buttons optional" type="radio" value="true" checked="checked" name="user[nurse_attributes][qualified]" id="user_nurse_attributes_qualified_true">Yes
</label>
</span>
<span class="radio">
<label for="user_nurse_attributes_qualified_false">
<input class="radio_buttons optional" readonly="readonly" type="radio" value="false" name="user[nurse_attributes][qualified]" id="user_nurse_attributes_qualified_false">No
</label>
</span>
</div>
<div id="denied-quote-one" style="display: none;">
<p class="p-red">Unfortunately we cannot give you a quote if your answer to this question is no. You will not be able to move forward.
</p>
</div>

AngularJS checkbox uncheck

How in angular when a checkbox is uncheck, the form data will be reset.
<div class="form-group">
<input type="text" verify-store ng-model="user.merchant_store_name" class="form-control" name="merchant.store_name" placeholder="Store Name" ng-model-options="{ updateOn: 'blur' }" required>
<div ng-if="signupForm.$pending.usernameExists">verifying....</div>
<div ng-if="signupForm.$error.usernameExists[0].$viewValue">
<label class="control-label" style="color:red">A store with that name already exists. Please select another name.</label>
</div>
<div class="form-group">
<input type="text" class="form-control" ng-model="user.merchant_mobile_phone" placeholder="Phone" >
</div>
</div>
<div class="checkbox clip-check check-primary">
<input type="checkbox" id="agree" ng-model="signupForm.agree" value="agree" ng-required="!signupForm.agree">
<label for="agree">I agree</label>
</div>
<div class="checkbox clip-check check-primary" ng-show="signupForm.agree">
<input type="checkbox" id="merchant" ng-model="signupForm.merchant" value="merchant" >
<label for="merchant">Sign up as merchant</label>
</div>
Is there a way this can be done within the view template rather than passing it to controller. Or should I write a directive for this?
Thanks!!
You don't have to write a single line in your controller to achieve your task with the following two DOM settings.
<input type="text" ng-model="myText">
<input type='checkbox' ng-model='chkMonitor' ng-click='!chkMonitor && (myText = "")' >
Explanation:
Your inputs are bound to the scope through scope variables. Now you place your code in ng-click of the check box to execute the clearing code. This has to be done only when the check box is unchecked. So, first check for this in a boolean expression before executing your clearing code :
ng-click='!chkMonitor && (myText = "")'
Your myText = "" will never execute as long as the chkMonitor is false.

Multi inputs which user can only enter in one of them

Consider a form which has many inputs, the inputs each has an radio button associated with them. User selects a radio and the associated input will be displayed.
http://jsfiddle.net/0uL6zzja/
If the number of inputs increase (for example 15) we will end up with lots of boilerplate code in js of all radio buttons ( they all do the same thing, disable other inputs, enable my input)
The js is as:
$('#precentRadio').change(function () {
$("#dolorsInput").attr("disabled", true);
$("#precentInput").attr("disabled", false);
})
$('#dolorsRadio').change(function () {
$("#precentInput").attr("disabled", true);
$("#dolorsInput").attr("disabled", false);
})
Are there any way which can can minimize the code ?!
Working demo
Use a class name for the buttons that trigger the inputs to disable/enable, and a class name for the inputs. Disable them all, and enable the one you want by traversing from the clicked button to the closest .input-group then back down to the input field.
jQuery (this is all)
$('.some-button').change(function () {
$('.some-input').prop("disabled", true);
$(this).closest('.input-group').find('.some-input').prop("disabled", false);
})
HTML
Please enter amount in "$" or "%":<p/>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">
<input name="switched" checked="checked" type="radio" class="some-button">
</span>
<div class="input-group input-group-applyed-input-manager">
<span class="input-group-addon">$</span>
<input class="form-control some-input" type="text" >
</div>
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">
<input name="switched" type="radio" class="some-button">
</span>
<div class="input-group input-group-applyed-input-manager">
<span class="input-group-addon">%</span>
<input class="form-control some-input" type="text" disabled>
</div>
</div>
</div>
(repeat)
Also disabled="true" isn't correct, it's not a boolean value in HTML, it's either there or not there, and you should use .prop() not attr() for disabled.
You can add a common class to your radio buttons and attach a single event to all of them. From there you can use DOM traversal to only change the related text input. Something like this:
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">
<input name="switched" class="input-toggle" checked="checked" type="radio" />
</span>
<div class="input-group input-group-applyed-input-manager">
<span class="input-group-addon">$</span>
<input class="form-control" type="text" />
</div>
</div>
</div>
$('.input-toggle').change(function() {
$('.input-group input[type="text"]').prop('disabled', true); // disable all
$(this).closest('.input-group').find('input[type="text"]').prop('disabled', false);
});
Example fiddle
Sure. The correct way to associate radio buttons with a similar function is to use a common name rather than a class. This makes the radio buttons mutually exclusive (so only one of the options in the group can be active at once).
Then, add the jQuery .change handler not to a single item but to all the radio buttons with that name $('input:radio[name=whatever]').change( ... );.
Inside the function, it is easy to write code which enables the text field directly following the radio button that was clicked, using jQuery's next() method, and disables all other text fields that follow other radio buttons in the group.
If you can't change the HTML, but the ids of the radio buttons and inputs will continue to match (xxxRadio and xxxInput), you can handle things by looking up the id of the selected radio button, and enabling the respective input:
$('input[name=switched]').change(
function() {
var selected = $('input[name=switched]:checked');
var selId = selected.attr('id');
var inpId = '#' + selId.replace(/Radio$/, 'Input');
var activeInput = $(inpId);
$('input.form-control').prop('disabled' ,true);
activeInput.prop('disabled', false);
}
);
#import url('http://getbootstrap.com/dist/css/bootstrap.css');
div.input-group > div.input-group > span.input-group-addon {
border-radius: 0px !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Please enter amount in "$" or "%":<p/>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">
<input name="switched" checked="checked" type="radio" id="dolorsRadio">
</span>
<div class="input-group input-group-applyed-input-manager">
<span class="input-group-addon">$</span>
<input class="form-control" type="text" id="dolorsInput">
</div>
</div>
</div>
<div class="col-sm-4">
<div class="input-group">
<span class="input-group-addon">
<input name="switched" type="radio" id="precentRadio">
</span>
<div class="input-group input-group-applyed-input-manager">
<span class="input-group-addon">%</span>
<input class="form-control" type="text" id="precentInput" disabled="true">
</div>
</div>
</div>

Categories