fadeIn/fadeOut <div> on radio and/or select option being selected - javascript

I cannot find a perfect solution for this.
Is there a simple way to fadeIn the ".filter_on" div, if I click on a select option and/or radio button?
And by default, get this div to fade out again afterwards?
My fiddle
<div class="filter">
Filter <span class="filter_on">active</span>
</div>
<form>
<p>Vehicle?</p>
<select name="vehicle" size="2">
<option>Bike</option>
<option>Car</option>
</select>
</form>
<form>
<p>City?</p>
<input type="radio" id="all" name="city" value="All" checked>
<label for="all"> All</label></input>
<input type="radio" id="ny" name="city" value="New York">
<label for="ny"> New York</label></input>
<input type="radio" id="mh" name="city" value="Manhattan">
<label for="mh"> Manhattan</label></input>
</form>

You don't need to fadeOut since you cannot unselect from drop-down or cannot uncheck the radio button.
$('select, :radio').on('change', function() {
if ($('select option:selected').length === 0 && $(':radio:checked').val() === 'All') {
$('.filter_on').fadeOut();
} else {
$('.filter_on').fadeIn();
}
}).trigger('change');
trigger will execute this function automatically. Will fadeIn on the page load.
Demo: https://jsfiddle.net/tusharj/vyd7a2s8/1/

Demo -> http://jsfiddle.net/vyd7a2s8/4/
var defaultRadio = $(':radio:checked');
var defaultVehicle = $('[name=vehicle] option:selected');
$('[name=vehicle],[name=city]').on('change', function (e) {
var currentRadio = $(':radio:checked');
var currentVehicle = $('[name=vehicle] option:selected');
if (currentRadio[0].isEqualNode(defaultRadio[0]) && currentVehicle[0].isEqualNode(defaultVehicle[0])) {
$('.filter_on').fadeOut(500);
} else {
$('.filter_on').fadeIn(500);
}
});
Explanation - This will store the default selected values outside the function and uses them inside the click event to check the newly selected values.

Related

Radio button needs to be clicked twice to initiate function

I am trying to call a function when a user uses either radio button on a produc page, but this functionality only works when the radio button is clicked twice on first load, then it switches between options with no problem. I have experiementated with various change, click functions and event handlers, but the result is the same.
//toggle subscription dropdown
const changeOptions = function() {
//When one-time option is selected
$("input[id='one_time']").on('click', function(e) {
//update checked status when one-time is selected
$("#one_time").attr('checked', 'checked');
$("#subscribe_plan").removeAttr('checked');
//show/hide logic is option is selected
if ($(this).attr("checked") === 'checked') {
formatName();
$('.js-price').html('<span class="money">' + (selectedVariant.price / 100).toLocaleString(undefined, {
minimumFractionDigits: 2,
maximumFractionDigits: 2
}) + '</span>');
currencyPicker.setCurrencyText();
Currency.convertAll(shopCurrency, Currency.currentCurrency);
document.querySelector('.js-selling-plan-id').setAttribute("name", '_');
document.querySelector('[name="_"]').value = '';
$('#selling_select').prop("disabled", true);
$('.subscribe_option').removeClass("d-block");
$('.subscribe_option').addClass("d-none");
};
});
//When subscription option is selected
$(document).on('change', "input[id='subscribe_plan']", function(e) {
//update checked status when subscribe is selected
$("#subscribe_plan").attr('checked', 'checked');
$("#one_time").removeAttr('checked');
//show/hide logic is option is selected
if ($(this).attr("checked") === 'checked') {
formatNameSelling();
const offerPrice = $('.js-price').attr('data-offer-price');
$('.js-price').html('<span class="money">' + offerPrice + '</span>');
currencyPicker.setCurrencyText();
Currency.convertAll(shopCurrency, Currency.currentCurrency);
const availableSellingPlanAllocations = selectedVariant.selling_plan_allocations;
const sellingPlan = availableSellingPlanAllocations[0].selling_plan_id;
document.querySelector('.js-selling-plan-id').setAttribute("name", 'selling_plan');
document.querySelector('[name="selling_plan"]').value = '';
$('#selling_select').removeAttr("disabled");
$('.subscribe_option').removeClass("d-none");
$('.subscribe_option').addClass("d-block");
}
$('select').each(function() {
$(this).val($(this).find("option[selected]").val());
// currencyPicker.loadCurrency();
// currencyPicker.setCurrencyText();
});
});
}
//end toggle subscription dropdown
//initiate the function
$(document).ready(function() {
changeOptions();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!--radio 1 -->
<input type="radio" class="" id="one_time" name="option" value="">
<label for="one_time" class="radio_label">
option 1
</label>
<!--radio 2 -->
<input type="radio" class="" id="subscribe_plan" name="option" value="" data-value="" checked="checked">
<label for="subscribe_plan" class="radio_label">
option 2
</label>
Here's an example that uses only css.
By default the div is hidden, but ehwn you select #one_time, it appears. You can add another one for the other option and it should work. Also alot less effor than all that JS.
.reveal {
visibility: hidden;
}
.radio #one_time:checked~.reveal {
visibility: visible;
}
<div class="form">
<div class="radio">
<input type="radio" id="one_time" name="option">
<label for="one_time" class="radio_label">
option 1
</label>
<input type="radio" id="subscribe_plan" name="option" checked="checked">
<label for="subscribe_plan" class="radio_label">
option 2
</label>
<div class="reveal">
<input type="text" name="menu" placeholder="Menu">
</div>
</div>
</div>

jquery radio button each -not working

i am trying to loop through the radio buttons by name with 'each' function..the each function is not working and it is applying the logic only once and it is not looping for the next time..
My use case is, when user selects value from the select dropdown, needs to enable both the radio buttons and if the user deselects the dropdown- needs to disable back..
Here in my case, each function is looping only once and after that it is getting exit from it..Need help in figuring disable/enable based on dropdown selection..
html code:-
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser" value="anyUser" name="authPermission" id="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser" value="groupUser" name="authPermission" id="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder" id="authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
jquery:
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(){
$("#authPermission").prop('disabled',false);
$("#authPermission").prop('checked',false);
});
}
else{
$("#authPermission").each(function(){
$("#authPermission").prop('disabled',true);
$("#authPermission").prop('checked',false);
});
}
});
You cannot have more than one element with the same ID. So, I would change your code by removing the id attribute and putting a new value for the class attribute, then fetch the object using jquery class selector.
<div class="uriDiv input-group">
<select class="common authSelect form-control" name="authType" id="authType">
<option value="">
<spring:message code="newPolicy.selectAuthType"></spring:message>
</option>
<option value="DB">DB</option>
<option value="LDAP">LDAP</option>
</select>
</div>
<td>
<div class="auth-permission-rd">
<div class="uriDiv radio radio-left">
<label>
<input type="radio" class="common anyuser authPermission" value="anyUser" name="authPermission" disabled="disabled">Any User
</label>
</div>
<div class="uriDiv radio radio-input">
<label>
<input type="radio" class="common groupuser authPermission" value="groupUser" name="authPermission" disabled="disabled">
<input type="text" name="authPermissionValue" disabled="disabled" class="common form-control-placeHolder authPermissionValue" placeholder="Enter custom Permissions - Comma separated" />
</label>
</div>
</div>
And jQuery code :
$("#authType").change(function(){
if($(this).val()){
$("input:radio[name='authPermission']").each(function(elemId, elem){
$(elem).prop('disabled',false);
$(elem).prop('checked',false);
});
}
else{
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
}
});
But, if we take a better look at your code, I do not understand why you want to use "each". You can achieve the same thing without it :
// Following code :
$(".authPermission").each(function(elemId, elem){
$(elem).prop('disabled',true);
$(elem).prop('checked',false);
});
// Does the same thing as this one :
$(".authPermission").prop('disabled', true).prop('checked', false);
I refactored your code. Also enables the input field when the appropriate radio is clicked. This sould work:
function updateUI() {
var select = $("#authType");
var value = select.val();
var should_appear = (value.length == 0);
$("input:radio[name='authPermission']").attr('disabled',should_appear);
}
//binding...
$("input:radio").on("click", function() {
var should_display_textbox = !($(this).val() === "groupUser");
console.log(should_display_textbox);
$("input:text[name='authPermissionValue']").attr('disabled', should_display_textbox);
});
$("#authType").change(function(){
updateUI();
});
$(document).ready(function() {
updateUI(); //update also when page load
});
Something like this maybe?
$("#authType").change(function(){
var disabled = !$(this).val() ? true : false;
$("input:radio[name='authPermission']").each(function(){
$(this).prop('disabled', disabled );
$(this).prop('checked',false);
});
});

How do I display a dropdown list on clicking a radio button?

I have a task where I have to display seperate dropdown lists for each option in radio buttons. When I select a radio button (not selecting a radio button and then clicking on 'submit'. Just selecting(clicking on) a radio button), the corresponding dropdown list should be displayed in the side.
You want to listen to the on 'change' event, this is an example with jquery:
$('select').hide();
$('input').on('change', function(){
$('select').show();
})
I've dropped a working example into jsbin: https://jsbin.com/xohecizina/edit?html,js,output
I made an example for you here.
The example is basically the following steps:
Mark up your HTML
<label>Radio 1</label>
<input type="radio" name="group" value="1" checked />
<label>Radio 2</label>
<input type="radio" name="group" value="2" />
<label>Radio 3</label>
<input type="radio" name="group" value="3" />
<div>
<select id="drop1">
<option>DropDown 1</option>
</select>
<select id="drop2" class="no-display">
<option>DropDown 2</option>
</select>
<select id="drop3" class="no-display">
<option>DropDown 3</option>
</select>
</div>
Add CSS
.no-display {display: none;}
Add event listeners to the radio buttons that call your drop-down selecting function
var radio_buttons = document.getElementsByName("group");
for (var i = 0; i < radio_buttons.length; i++) {
radio_buttons[i].addEventListener("change", setDropDown);
}
function setDropDown() {
setDropDownsForNoDisplay();
if (this.checked) {
setDropDownForDisplay(this.value);
}
}
Add helper functions that the drop-down selecting function uses
var dropdowns = document.getElementsByTagName("select");
function setDropDownsForNoDisplay() {
for (var i = 0; i < dropdowns.length; i++) {
dropdowns[i].classList.add("no-display");
}
}
function setDropDownForDisplay(x) {
if (x === "1") {
document.getElementById("drop1").classList.remove("no-display");
} else if (x === "2") {
document.getElementById("drop2").classList.remove("no-display");
} else if (x === "3") {
document.getElementById("drop3").classList.remove("no-display");
}
}
You could also use events ("onclick", "onchange") directly in the radio button markup instead of adding event listeners, but I prefer keeping my events separated from the markup.

Check if Checkbox is checked based on name

This is my code and it always returns "nothing is checked" no matter if something is checked or not.
function rstSelfs() {
var chkds = document.getElementsByName('selfs');
if(chkds.checked)  {
alert ("something is checked"); }
else {
alert("nothing is checked");
}}
I have been using the above as a test to see if I can get the code to work properly. I have multiple checkboxes with the name "selfs" and I want the dropdown selection only to reset if none of the boxes with the name "selfs" are not checked. I would assume the code would look like this but nor this or the code above works... Please help.. I new to this and I have attempted to search and it is possible this has been answered but I apologize it did not name sent to me.
What I want the code to do is this:
function rstSelfs() {
var chkds = document.getElementsByName('selfs');
if(chkds.checked)  {
return false; }
else {
($('.CssSel').get(0).selectedIndex = 0) }
}
<form id="Service">
<input type="checkbox" name="site" id="cktmcom" onclick="isTsite()">
<input type="checkbox" name="selfs" id="ckselfc" onclick="isTsserv();isTextServC()">
<label for="checkbox">Self-Serve Classic</label><br>
<input type="checkbox" name="selfs" id="ckselfn" onclick="isTsserv();isTextServN()">
<label for="checkbox">Self-Serve Next-Gen</label><br>
<input type="checkbox" name="homeSer" id="ckhomes" onclick="isThs()">
<label for="checkbox">Home Services</label><br>
<input type="checkbox" name="mapp" id="ckmobilea" onclick="isTmApp()">
<label for="checkbox">Mobile App</label><br>
<input type="checkbox" name="checkbox" id="ckgem" onclick="isTextGem()">
<label for="checkbox">Gemini</label><br>
</form>
<form id="Service2">
<input type="checkbox" name="site" id="ckkmcom" onclick="isKsite()">
<label for="checkbox">mobile.com</label><br>
<input type="checkbox" name="selfs" id="ckKselfc" onClick="isKsserv();isKServC()">
<label for="checkbox">M Self-Serve Classic</label><br>
<input type="checkbox" name="selfs" id="ckKselfn" onClick="isKsserv();isKServN()">
<label for="checkbox">M Self-Serve Next-Gen</label><br>
<input type="checkbox" name="mapp" id="ckKmobilea" onclick="isKmApp()">
<label for="checkbox">M Mobile App</label><br>
</form>
The checkboxes with name "selfs" control the hide and show for the div = selfserve.
And I need to reset the drop down selection only if none of the "selfs" are chcked .
I have actually have 5 checkboxes that have the name selfs. The code is rather large thats why the other 3 are missing.
The HTML dropdown code is:
<div id="selfserve" style="display:none">
<select class="CssSel" style="width:175px" onChange="ssPicker()">
<option value="1" selected style="color:red;" ssSel="**Self-Serve Issue**">Select Self-Serve
Issue</option>
<option value="2" ssSel="Entire Site Down">Entire Site Down</option>
<option value="3" ssSel="Login Issues">Login Issues</option>
<option value="4" ssSel="Usage Meter Issue">Usage Meter Issue</option>
<option value="5" ssSel="Change feature Issues">Change feature Issues</option>
<option value="6" ssSel="Page Loading Issues">Page Loading Issues</option>
<option value="7" ssSel="Extreme Latency">Extreme Latency</option>
<option value="8" ssSel="Navigation Issues">Navigation Issues</option>
</select>
</div>
<input type="button" name="reset_self" value="Reset" onClick="rstSelfs()">
Not working:
Since you use jQuery, you can check if any checkboxes are not checked:
function rstSelfs() {
var chkds = $("input[name='selfs']:checkbox");
if (chks.not(":checked").length > 0) {
return false;
} else {
($('.CssSel').get(0).selectedIndex = 0)
}
}
this worked but I had to rework it a bit! thank you!
Tweaked, working:
function rstSelfs() {
var chkds = $("input[name='selfs']:checkbox");
if (chkds.is(":checked")) {
return false;
} else {
($('.CssSel').get(0).selectedIndex = 0)
}
}
getElementsByName() function returns an array of elements, not single element, so it doesn't have property checked. If there is only one element by this name you should use something like this:
document.getElementsByName("selfs")[0].checked
Or to correct your function:
function rstSelfs() {
var chkds = document.getElementsByName('selfs')[0];
if(chkds.checked) {
alert ("something is checked"); }
else {
alert("nothing is checked");
}}
Since you have more than one checkbox with same name , you will get array when you do document.getElementsByName('selfs') . Try looping through the resulting array to see if any of that is checked.
Something like this :-
var isChecked=false ;
for (i=0; i<document.Service.selfs.length;i++) {
if(document.Service.selfs[i].checked)
isChecked=true ;
}
if(isChecked) ($('.CssSel').get(0).selectedIndex = 0)

jquery in yii: Detecting radiobutton losing check mark (checked state)

Given the following code (yes, i know it is perhaps irrelevant in yii, but I added the tag so I update the question with the actual generated html):
<script>
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
}).change();
});
</script>
<div id="widgetId-dialog">
<form id="widgetId-form" action="/support/test" method="post">
<div>
<input id="valueType-single" value="single" data-class="singleValueField" checked="checked" type="radio" name="valueType" />
<label for="single">Valor simple</label>
<input size="6" class="singleValueField" type="text" value="" name="singleValue" id="singleValue" />
</div>
<div>
<input id="valueType-range" value="range" data-class="rangeValueField" type="radio" name="valueType" />
<label for="range">Rango (inicio:fin:intervalo)</label>
<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_start" id="rangeValue_start" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_end" id="rangeValue_end" />:<input size="6" class="rangeValueField" type="text" value="" name="rangeValue_interval" id="rangeValue_interval" />
</div>
</form>
</div>
It doesn't trigger change() when a radio becomes unchecked. This implies: controls are disabled only on initialization (.ready()). change() is not triggered individually by controls losing the checkmark.
Question: how can I detect when a radio button loses the checkmark?
This is a conceptional problem. The radio buttons are seen somehow like one element. For closer information look at Why does jQuery .change() not fire on radio buttons deselected as a result of a namesake being selected?.
So the change-event will always only fire on the newly selected element and not on the deselected radios. You could fix your code like this:
$(function(){
$('#widgetId-form input[name="valueType"]').change(function(){
//could be also hardcoded :
$('input[name="' + $(this).attr("name") + '"]').each(function(){
if ($(this).is(":checked"))
{
console.log("habilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", false);
}
else
{
console.log("deshabilitando "+$(this).data("class"));
$("."+$(this).data("class")).prop("disabled", true);
}
});
});
$('#widgetId-form input[name="valueType"]:first').change();
});
You can check it at http://jsfiddle.net/jg6CC/. Greets another Luis M. ;)

Categories

Resources