Radio button needs to be clicked twice to initiate function - javascript

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>

Related

Remove part of form when checkbox is checked

I'm trying to make a form that will hide and show some parts of the form. It working correctly in some tries. But when the user chooses and checks an option with class badCheckbox which is showing badField subsequently then user checks option without class badCheckbox which should showing 'goodField' than 'badField' is not hiding and still is shown.
And when a user tries to check options separately all work correctly only in upper mentioned case.
Is there any way to do it?
//Script to hide and show div
$('.badCheckbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
if (this.checked) {
checked += 1;
}
});
if (checked != 0) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
//script to check only one of three
$(".oneChecked").on('click', function() {
// in the handler, 'this' refers to the box clicked on
var $box = $(this);
if ($box.is(":checked")) {
var group = "input:checkbox[name='" + $box.attr("name") + "']";
$(group).prop("checked", false);
$box.prop("checked", true);
} else {
$box.prop("checked", false);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
here is a short version
$('#checks').on('change', 'input[name="checkin"]', function (){
if( $(this).is(':checked') ){
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', true);
} else {
$('#checks .oneChecked:checked').prop('checked', false);
$(this).prop('checked', false);
}
if( $('#checks .badCheckbox:checked').is(':checked') ){
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="checks">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="oneChecked"/>
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit"/>
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit"/>
</div>
Consider the following improvements.
$(function() {
function checkStuff(checked) {
if (checked) {
$('#badField').show();
$('#goodField').hide();
} else {
$('#badField').hide();
$('#goodField').show();
}
}
//script to check only one of three
$(".boxes").on('change', ".oneChecked", function() {
if ($(this).is(":checked")) {
$(".boxes input[type='checkbox']").prop("checked", false);
$(this).prop("checked", true);
checkStuff($(this).is(".badCheckbox"));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="boxes">
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked badCheckbox" />
<input name="checkin" type="checkbox" class="oneChecked" />
</div>
<div id="badField" style="display:none;">
<p>:((</p>
<input type="submit" />
</div>
<div id="goodField">
<p>NICE!!!</p>
<input type="submit" />
</div>
it's because you don't have an event when user click and the third checkbox.
Your function to show/hide message work when there are an update (change) on an input with the class .badCheckbox but when you click on the third (where doesn't have the class) your function is not called.
I think you should have a class on all your checkbox and use it in your function who lister the change.
Something like this :
$('.checkbox').change(function() {
let checked = 0;
$('.badCheckbox').each(function() {
// ...
});
And your html
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked badCheckbox"/>
<input name="checkin" type="checkbox" class="checkbox oneChecked"/>
There is a lot of optimization that can be done to improve your code, like using the radio to remove your oneChecked function or printing the right message when the checkbox is checked instead of using show/hide two div but i think you should see it in the future
I hope this can help you and welcome to StackOverflow
First of all, obviously your checkboxes have to act like radios. As I understand, that is what you want to do. So, I modifyed your script a little bit to make checkboses to act as they are radio inputs, and in the same time to show/hide paragraph, depending on if clicked element has class badCheckbox and it's state (checkd or not). Here is the result:
//Script to hide and show div
$('.oneChecked').click( (everyOne) => {
//handles click (and change) on every element with class oneChecked
//they all has it in your example
$('.oneChecked').each( (ind, currentOne) => {
//iterate to all elements with class oneChecked
//and compare if matches clicked one
if ( !$(currentOne).is($(everyOne.target)) ) {
//other instance, not clisked one, so clear it
//to simulate behaviour of radio input
$(currentOne).prop('checked', false);
}
});
//checks if clicked element is bad or not and show/hide your p
if ($(everyOne.target).hasClass('badCheckbox') && $(everyOne.target).prop('checked')){
console.log('b-s/h');
$('#badField').show();
$('#goodField').hide();
} else {
console.log('s/b-h');
$('#badField').hide();
$('#goodField').show();
}
});
Here is an workign example in CodePen: https://codepen.io/kalatchev/pen/gOpJBOv

Why the input never change the disabled attribute?

I want to enable/disable an input type="number" but it never changes.
It starts disabled and when I press a input type="radio" I want to enable it.
<input type="number" class="form-control filtros_mapa_ruta" id="n_nodes_ruta" value="2" min="1" disabled>
I see a lot of people have this problem and they usually try with $('input').attr("disabled", true); but is failing too.
The jQuery function, using .prop("disabled", true):
$("#radio_ult_pos").on('click', function() {
if ($('#radio_ult_pos').is(':checked')) {
$( ".filtros_mapa_ruta" ).checkboxradio( "disable" );
$('#n_nodes_ruta').prop("disabled", true);
}
});
$("#radio_ruta").on('click', function() {
if ($('#radio_ruta').is(':checked')) {
$( ".filtros_mapa_ruta" ).checkboxradio( "enable" );
$('#n_nodes_ruta').prop("disabled", false);
}
});
Snippet (the checkbox here is not working because I'm using a jQuery UI widget, but they're working well in my code):
function checkboxController() {
$("#radio_ult_pos").on('click', function() {
if ($('#radio_ult_pos').is(':checked')) {
$(".filtros_mapa_ruta").checkboxradio("disable");
$('#n_nodes_ruta').prop("disabled", true);
}
});
$("#radio_ruta").on('click', function() {
if ($('#radio_ruta').is(':checked')) {
$(".filtros_mapa_ruta").checkboxradio("enable");
$('#n_nodes_ruta').prop("disabled", false);
}
});
}
$(document).ready(function() {
checkboxController();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-2" id="filter_container">
<!-- FILTROS-->
<legend>Filtros mapa: </legend>
<label for="radio_ult_pos">Última posición</label>
<input type="radio" name="radio_select" class="filtros_mapa" id="radio_ult_pos" checked>
<label for="radio_ruta">Ruta</label>
<input type="radio" name="radio_select" class="filtros_mapa" id="radio_ruta">
<legend id="legend_filtro_datos">Filtros datos: </legend>
<label for="checkbox-2">Goat tracker 1</label>
<input type="checkbox" name="GOAT_TRACKER1" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-2" disabled>
<label for="checkbox-3">Goat tracker 2</label>
<input type="checkbox" name="GOAT_TRACKER2" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-3" disabled>
<label for="checkbox-4">Goat tracker 3</label>
<input type="checkbox" name="GOAT_TRACKER3" class="filtros_mapa filtros_mapa_ruta filtros_mapa_ruta_checkb optionNodeFilter" id="checkbox-4" disabled>
<input type="number" class="form-control filtros_mapa_ruta" id="n_nodes_ruta" value="2" min="1" disabled>
<button type="button" class="btn btn-success" id="filtrar_btn_map">Filtrar</button>
</div>
I tried with $('#n_nodes_ruta').removeAttr("disabled") but is not working too...
Why never change the attribute disabled?
In JS, you can set an event listener on the container div and if the radio buttons are clicked, you can set the disabled property on the input to true or false.
const input = document.getElementById("n_nodes_ruta");
function checkboxController() {
document.querySelector('.col-2').addEventListener('click', () => {
if(event.target.id === "radio_ult_pos") {
input.disabled = true;
}
else if(event.target.id === "radio_ruta") {
input.disabled = false;
}
})
}
$(document).ready(function() {
checkboxController();
});
As #Heretic Monkey said the problem was the jQuery function checkboxradio.
Yes, it was defined, but the problem was that the class filtros_mapa_ruta has the input as well, and that made him fail.
The solution was to call the right class, only with the checkbox.
$(".filtros_mapa_ruta_checkb" ).checkboxradio( "disable");
Thank you
you can simply use .attr('disabled', 'disabled') to make it disabled and .removeAttr('disabled') to enable it.

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

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.

Combining show/hide toggle with radio buttons AND checkboxes

I can toggle the show/hide of a checkbox because it can be unchecked but the behavior is different on a radio group because clicking a checked radio button doesn’t uncheck it, only clicking another radio button in the same group.
DEMO WORKS FOR CHECKBOX NOT RADIO GROUPS
How can I modify this so it works for radio buttons and checkboxes in the same function? In this example I can click Item4 but it doesn’t hide upon clicking the others in the radio group.
How it should work:
Put data-info-id="infox" on the input
Put id="infox" on the container usually a div
jQuery solutions are welcome.
HTML
<input type="checkbox" id="item1" data-info-id="info1" />
<label for="item1">Item 1 Checkbox</label>
<br/>
<div id="info1">Content checkbox group</div>
</p>
<input type="radio" id="jb1" name="jb" />
<label for="jb1">Item2 Radio</label>
<br/>
<input type="radio" id="jb2" name="jb" />
<label for="jb2">Item3 Radio</label>
<br/>
<input type="radio" id="jb3" name="jb" data-info-id="info2" />
<label for="jb3">Item4 Radio</label>
<br/>
<div id="info2">Content radio group</div>
CSS
[id^="info"] {
display: none;
}
JS
document.addEventListener('change', function(e) {
var id = e.target.getAttribute('data-info-id');
var checked = e.target.checked;
if (id) {
var div = document.getElementById(id);
if (div)
div.style.display = checked ? 'block' : 'none';
}
});
I first added two containing divs around the checkbox and the radio buttons:
<div id="checkbox">
<input type="checkbox" id="item1" data-info-id="info1" />
<label for="item1">Item 1 Checkbox</label>
</div>
<br/>
<div id="info1">Content checkbox group</div>
</p>
<div id="radios">
<input type="radio" id="jb1" name="jb" />
<label for="jb1">Item2 Radio</label>
<br/>
<input type="radio" id="jb2" name="jb" />
<label for="jb2">Item3 Radio</label>
<br/>
<input type="radio" id="jb3" name="jb" data-info-id="info2" />
<label for="jb3">Item4 Radio</label>
<br/>
</div>
<div id="info2">Content radio group</div>
I then added a for loop to loop through the children of the parent of the item clicked. Because it was only triggering the change event for the clicked item.
document.addEventListener('change', function (e) {
var children = e.target.parentNode.children;
for(var i = 0; i < children.length ; i ++)
{
var id = children[i].getAttribute('data-info-id');
var checked = children[i].checked;
if (id) {
var div = document.getElementById(id);
if (div) div.style.display = checked ? 'block' : 'none';
}
}
});
This works for me. It's a little down and dirty but it works just fine.
For the radio buttons. This can be done in 2 ways :
Here's the jsFiddle : http://jsfiddle.net/zvzL8u1n/
Method1
Have 2 radio buttons Show and Hide.
$("input[name=jbM1]").change(function(){
$("#" + $(this).data("info-id")).toggle();
});
jbM1 is the name for both the radio buttons.
So basically data-info-id is given in both the radio buttons and on their change the div is toggled.
Method2
Have only one radio button and make it work like checkbox
$("#jb3").click(function(){
var prev = $(this).data('prev');
if(prev == true){
$(this).prop('checked', false);
}
$(this).data('prev', $(this).prop('checked'));
$("#" + $(this).data("info-id")).toggle();
});
jb3 is id of the radio button and data-prev is used for storing prev value.

using multiple sets of radio buttons, how can I unhide and hide images

Images //hide and show images with buttons
images are shown based on radio button/checkbox selected
<img id="storage_drawer" src="images/placeholder/get_hardware/storage_drawer.png" />
<img id="cash_drawer" src="images/placeholder/get_hardware/cash_drawer.png" />
Form two sets of radio buttons// changed into checkboxes by javascript function
<input type="checkbox" id="cashdrawer" name="type" value="cashDrawer" class="unique" >
<input type="checkbox" id="cashStorage" name="type" value="storageDrawer" class="unique">
//second set of radio buttons
<input type="checkbox" id="single" name="type2" value="singleLine" class="unique" >
<input type="checkbox" id="multi" name="type2" value="multiLine" class="unique" >
</form>
Start of script
$(document).ready(function(){
to make make checkboxes have the functionality of radio buttons
var $inputs = $(".unique");
$inputs.change(function(){
$inputs.not(this).prop('checked');
});
return false;
radio buttons -- first set of radio buttons
$("input[name$=type]").click(function(){
var value = $(this).val();
//Cash Drawers
if(value == 'cashDrawer') {
$("#cash_drawer").show();
$("#storage_drawer").hide();
}
else if( value == 'storageDrawer') {
$("#storage_drawer").show();
$("#cash_drawer").hide();
}
})
$("#cash_drawer").hide();
$("#storage_drawer").hide();
second set of radio buttons
$("input[name$=type2]").click(function(){
var value = $(this).val();
//Barcode Scanners
if(value = 'singleLine') {
$("#sinlgeBarcode").show();
$("#multiBarcode").hide();
}
else if(value == 'multiLine') {
$("#multiBarcode").show();
$("#sinlgeBarcode").hide();
}
})
$("#sinlgeBarcode").hide();
$("#multiBarcode").hide();
});
});
end of script
If your radio boxes have the same name attribute they will behave as radio buttons i.e only one selection can be active in the group, but if each button have their own name they can all be selected.
So if u have a collection of radios like this:
<form>
<input type="radio" name="1">
<input type="radio" name="2">
<input type="radio" name="3">
</form>
U can get them to behave like check boxes with a lil javascript:
// This will allow the radio boxes to toggle on of.
$("input[type=radio]").click(function(){
$(this).attr("checked", !$(this).attr("checked"));
});
Edit:
I did a js fiddler with a working example, maybe it will give some answers.
http://jsfiddle.net/uPp82/1/

Categories

Resources