Javascript show div when all radio button is checked - javascript

I have a code that can show div everytime I click a radio button and it is working fine. The problem is I want all the radio button be checked and then the div will show.
Here is my code for 1 radio button
function showstuff(nxt){
document.getElementById(nxtb).style.display="block";
}
<input id="ny" name="ny" type="radio" onClick="document.getElementById('ny').checked =
true; showstuff('nxt');" />
<div id="nxtb">Next</div>
Thanks in advance

Here is a solution without an obtrusive JavaScript (that is onclick attributes):
/*
* Convert to array so we can use `forEach()` and `every()`
*/
function toArray(any) {
return Array.prototype.slice.call(any);
}
var observed = toArray(document.querySelectorAll('[data-observe]'));
var listened = [];
var result = document.querySelector('#result');
/*
* Gather all elements we want to listen for change:
* observed elements and their siblings with the same name
*/
observed.forEach(function (target) {
var siblings = toArray(document.querySelectorAll('[name=' + target.name +']'));
listened = listened.concat(siblings);
});
listened.forEach(function (radio) {
radio.addEventListener('change', function () {
var checked = observed.every(function (item) {
return item.checked;
});
checked ?
result.removeAttribute('hidden') :
result.setAttribute('hidden', 'true');
});
});
Demo: http://jsfiddle.net/sZHAA/1/

Related

Prefill checkbox via link and preserve form function

I currently have a form i built that is 3 large check boxes, when selected they toggle the continue button below them, https://staging-homecarepulse.kinsta.cloud/demo-select/ this is the link so you can check it out.
Currently im trying to add functionality to the form that when you click a link from another page, it preselects the checkbox depending on the link selected.
I was able to find a script that allows me to setup a link with a hash ( https://staging-homecarepulse.kinsta.cloud/demo-select/#checkbox1 ) but my issue is that I cannot get the continue button to trigger when the form is accessed this way.
here is my code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var hash = location.hash;
if(hash=="#checkbox1"){
$("#checkbox1").prop("checked", !$("#checkbox1").prop("checked") ); // that toggles the checked state
}
});
</script>
<script>
$(document).on("change", ".mod-link", function() {
var arr = []
$(".mod-link:checked").each(function() {
arr.push($(this).val());
})
if (arr.length > 0) {
$('#picture').attr('src', '');
} else {
$('#picture').attr('src', 'https://staging-homecarepulse.kinsta.cloud/wp-content/uploads/2021/06/greyBTN.jpg');
}
var vals = arr.join(",")
var str = "/demo/?demo_request_type=" + vals;
var link = arr.length > 0 ? '<a class="dynabtn" href="'+str+'">Continue</a>': '' ;
$('.link-container').html(link);
});
</script>
anyone have any idea how i can use links like https://staging-homecarepulse.kinsta.cloud/demo-select/#checkbox1 to trigger that checkbox and still have the continue button toggle on?
Instead of trying to toggle the checked property, fire a click event on your checkbox.
$(document).ready(function() {
if (location.hash) {
let $checkbox = $(location.hash);
if ($checkbox.length) $checkbox.click();
}
});
Your Continue button will toggle as well.

Clicking Container Containing Checkbox - JQuery

I have a dropdown menu on a site that needs the label, checkbox, and container all clickable to activate the checkbox (and update the label of the element.
I have used e.stopPropogation, e.stopImmediatePropagation, and e.preventDefault (and usually preventDefault and stopPropagation together.)
My current code is below. It works on desktop (and responsive desktop in Chrome) just fine; but NOT on iOS. Any thoughts?
// Get the filter label.
var label = $('#edit-f-wrapper .edit-areas-link').data('filter-label');
// Element used to hold the label.
var title = $('#edit-f-wrapper .edit-areas-link label');
// Get a list with all checkboxes.
var checkboxes = $('#edit-f-wrapper input:checkbox');
// Click triggers
var clickTrigger = $('.form-type-bef-checkbox');
// Determine click action to take depending on browser/device
var action = ('ontouchend' in window) ? 'touchend' : 'click';
var checkBoxID = 'input[id^="edit-f-rc-core-cat-evrn-svgeographic"';
// Act on checkbox click - check if action is set, if not, set it to default click
clickTrigger.one(action, function (e) {
e.stopImmediatePropagation();
// Get child of clicked element
var checkboxChild = $(this).children("input[type=checkbox]").eq(0);
// Check it if the checkbox itself wasn't clicked
checkboxChild.prop('checked', !checkboxChild.prop('checked')).change();
}).on(action, checkBoxID, function(e) {
e.stopImmediatePropagation();
e.preventDefault();
// Check it if the checkbox itself wasn't clicked
$(this).prop('checked', !$(this).prop('checked')).change();
}).on(action, "label", function(e) {
e.stopImmediatePropagation();
e.preventDefault();
var checkboxChild = $(this).parent().children("input[type=checkbox]").eq(0);
// Check it if the checkbox itself wasn't clicked
checkboxChild.prop('checked', !checkboxChild.prop('checked')).change();
});
// When we have a change of state...
$(checkBoxID).on('change', function() {
console.log("Changed!");
// Update the title to reflect how many items have been checked.
var items = [];
checkboxes.each(function () {
var checkbox = $(this);
if (checkbox.prop('checked')) {
items.push(checkbox.next('label').html());
}
})
// Update the label data.
if (!items.length) {
title.html(label);
}
else if (items.length === 1) {
title.html(label + ': ' + items[0]);
}
else {
title.html(label + ': ' + items.length + ' selected');
}
});
And, the HTML markup:
<div class="form-item form-type-bef-checkbox form-item-edit-f-rc-core-
cat-evrn-svgeographicarch-cape">
<input type="checkbox" name="f[]" id="edit-f-rc-core-cat-evrn-svgeographicarch-cape" value="rc_core_cat_evrn_svgeographic:Arch Cape">
<label class="option" for="edit-f-rc-core-cat-evrn-svgeographicarch-cape">Arch Cape</label>
</div>

Toggle a Bootstrap Toggle element with JavaScript (and show animation)

I have a Bootstrap Toggle element as follows:
<input id="neutralInd" type="checkbox" name="neutralSite" onchange="setEventSite('neutral')" data-toggle="toggle" data-on="Yes" data-off="No">
Upon clicking it, it will toggle between Yes and No, and it successfully executes a JavaScript function that does other stuff (code below).
Here's what I want to do:
Upon selecting a Radio Button elsewhere on the page, it will execute JavaScript that toggles the Bootstrap Toggle to No. Here is the code I have so far:
Defining the radio buttons:
<div class="radio">
<label><input type="radio" id="homeTeam<?php echo $row; ?>" name="homeTeam" onchange="setEventSite('team')"></label>
</div>
JavaScript function code:
function setEventSite(chosen) {
var neutralInd = document.getElementById("neutralInd"); // Toggle
var locationOverride = document.getElementById("locationOverride"); // Text field
var homeTeam = document.getElementsByName("homeTeam"); // Radio buttons
if (chosen == "neutral") { // Toggle was clicked (changed)
if (neutralInd.checked) {
locationOverride.readOnly = false;
for(var i=0; i<homeTeam.length; i++) { homeTeam[i].checked = false; }
}
else {
locationOverride.value = "";
locationOverride.readOnly = true;
}
} else if (chosen == "team") // Radio button was selected
{
neutralInd.checked = false;
neutralInd.value="off";
locationOverride.value = "";
locationOverride.readOnly = true;
}
}
When I choose a Radio Button, it successfully sets the Text field to Readonly, but the Bootstrap Toggle does not appear to toggle (it remains set to Yes when it should switch to No). However, when I click the Toggle again, it stays on Yes yet executes the JavaScript as if it were being set to Yes. So that makes me think the value of the Toggle is successfully being set to No when I select a Radio Button, but the Toggle isn't displaying/animating the toggle to No. So maybe I'm asking how to make the Toggle show the animation of toggling to No.
Thanks!
Figured it out with the help of a good friend.
I needed to add the "off" class to the parent element of the Toggle when the radio button was selected. So I had to add 2 lines to the function, and it works as desired:
var parentInd = $("#neutralInd").parent();
parentInd.addClass("off");
So here is the resulting function code:
function setEventSite(chosen) {
var neutralInd = document.getElementById("neutralInd");
var locationOverride = document.getElementById("locationOverride");
var homeTeam = document.getElementsByName("homeTeam");
var parentInd = $("#neutralInd").parent();
if (chosen == "neutral") {
if (neutralInd.checked) {
locationOverride.readOnly = false;
for(var i=0; i<homeTeam.length; i++) { homeTeam[i].checked = false; }
}
else {
locationOverride.value = "";
locationOverride.readOnly = true;
}
} else if (chosen == "team")
{
neutralInd.checked = false;
neutralInd.value="off";
parentInd.addClass("off");
locationOverride.value = "";
locationOverride.readOnly = true;
}
}

Disable <a class button if input fields empty

I know it's easy to do using < button > or < input type="submit" but how would you keep this button disabled unless both input fields are filled?
<input id="one" type="text">
<input id="two" type="text">
OK
Tie an event to both inputs, and check that both have values. Then enable the link.
$('#one, #two').blur(function() {
if($('#one').val() !== "" && $('#two').val() !== "") {
$('.button').attr('href','#');
} else {
$('.button').removeAttr('href');
}
});
and change your html to:
<a class="button">OK</a>
so that the link is disabled on page load. Here's a JSFiddle demo.
$(document).ready(function() {
$inputs = $('#one,#tow');
$inputs.change(check);
$submit = $('#submit');
function check() {
var result = 1;
for (var i = 0; i < $inputs.length; i++) {
if (!$inputs[i].value) {
result = 0;
break;
}
}
if (result) {
$submit.removeAttr('disabled');
} else {
$submit.attr('disabled', 'disabled');
}
}
check();
});
suggest use angular form
$(document).ready(function(){
//$(".button").attr('disabled', "disabled");
$(".button").click(function(){
one = $("#one").val();
two = $("#two").val();
if(one && two){
///both fields filled.
return true;
}
//one or both of them is empty
return false;
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="one" type="text">
<input id="two" type="text">
OK
This is my implementation if facing this kind of situation.
First, am add disabled class onto anchor tag on page load by using this style :
.disabled {
color : gray // gray out button color
cursor : default; // make cursor to arrow
// you can do whatever styling you want
// even disabled behaviour
}
We add those class using jquery on document ready together with keyup event like so :
$(function () {
// add disabled class onto button class(anchor tag)
$(".button").addClass('disabled');
// register keyup handler on one and two element
$("#one, #two").keyup(function () {
var one = $("#one").val(),
two = $("#two").val();
// checking if both not empty, then remove class disabled
if (one && two) $(".button").removeClass('disabled');
// if not then add back disabled class
else $(".button").addClass('disabled');
});
// when we pressing those button
$('.button').click(function (e) {
// we check if those button has disabled class yet
// just return false
if ($(this).hasClass('disabled')) return false;
});
});
DEMO

Disable submit button until one in a group of dynamically-created radio buttons selected

I would like to disable a submit button until one of a group of radio buttons is selected. I know there are similar questions out there, but none pertain to a dynamically-created group of radio buttons...
Here is what I have.. a script at the top of the page generates a number of buttons given a user upload in a previous view:
var jScriptArray = new Array(#ViewBag.ColNames.Length);
var array = #Html.Raw(Json.Encode(ViewBag.ColNames));
for( var i = 0; i < #ViewBag.ColNames.Length; i++ ) {
jScriptArray[i] = array[i];
}
var length = #(ViewBag.NCols);
$(document).ready(function () {
for (var i = 0; i < length; i++) {
$('#radioGroupBy').append('<input id="grp' + i +'" type="radio" name="group" value="'+i+'">'+jScriptArray[i]+'</input>')
$('#radioGroupBy').append('<p style="padding:0px;margin:0px;"></br></p>');
}
});
This works, and selecting any of the buttons returns the proper value; great. However, I want to disable the submit button until one of these radio buttons is selected. Using an answer I found on SO earlier, I created the following (this works, but only if I hard code the group of buttons. The issue is it won't work with the Javascript-created group):
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
Also, for the sake of thoroughness, here is the submit button:
<input id="submitbtn" name="submitbtn" type="submit" value="Drill Down" disabled="disabled" />
Thanks so much!
Event delegation (also, use .prop() when removing the disabled property to the submit button)
$("#radioGroupBy").on("change", ":radio[name=group]", function() {
var $radioButtons = $(":radio[name=group]");
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
$("input[name='submitbtn']").prop("disabled", false);
}
});
I figured it out. As Benjamin suggested in comments above, the latter script was executing before the DOM was ready. I solved it by just surrounding the whole script in $(window).load... :
$(window).load(function () {
var $radioButtons = $("input[name='group']");
$radioButtons.change(function () {
var anyRadioButtonHasValue = false;
// iterate through all radio buttons
$radioButtons.each(function () {
if (this.checked) {
// indicate we found a radio button which has a value
anyRadioButtonHasValue = true;
// break out of each loop
return false;
}
});
// check if we found any radio button which has a value
if (anyRadioButtonHasValue) {
// enable submit button.
$("input[name='submitbtn']").removeAttr("disabled");
}
});
});

Categories