Show/hide on checkbox click does not work consistently - javascript

I am building an inspection app to walk an inspector through a house with context-relevant questions based on answers. I am having inconsistent success with using checkboxes to show/hide div content.
I have simplified my problem down to a few very basic lines of code that I can't seem to troubleshoot.
<input type="checkbox" name="cbReplaceOrRepair_0" value="Replace" id="cbReplaceOrRepair_0" onclick="showReplaceRoof()">Replace
<div class="dvRoofReplace" id="dvReplaceRoof" style="display:none">"Replace" option is checked</div><br>
<input type="checkbox" name="cbReplaceOrRepair_1" value="Repair" id="cbReplaceOrRepair_1" onclick="showDvConfirmRepairability()">Repair
<div class="dvRoofRepair" id="dvConfirmRepairability" style="display:none">"Repair" option is checked</div>
<script type="text/javascript">
function showReplaceRoof() {
var dvReplaceRoof = document.getElementById("dvReplaceRoof");
dvReplaceRoof.style.display = cbReplaceOrRepair_0.checked ? "block" : "none";
}
function showDvConfirmRepairability() {
var dvRoofRepair = document.getElementById("dvRoofRepair");
dvRoofRepair.style.display = cbReplaceOrRepair_1.checked ? "block" : "none";
}
</script>
My example shows one checkbox that works to show/hide a div and another on that does not work. Can anyone tell me what I'm doing wrong?
Also, this is my first question on here after literally years of looking up questions so I'll apologize in advance in case I messed up any of the posting protocols.
https://codepen.io/stephenskrocki/pen/EGoYaB

You access the element incorrectly.
The id of the second hidden element is id="dvConfirmRepairability.
Use var dvRoofRepair = document.getElementById("dvConfirmRepairability");
Hope this helps!!

Since there is only one wanted option, instead of checkbox I would use radio buttons:
HTML Markup:
<style>label > span {display: none;} /* hide notes by default */</style>
<label for="replace">Replace
<input type="radio" name="radio" id="replace" onchange="radio()" />
<span class="note">"Replace" option is checked</span>
</label>
<label for="repair">Repair
<input type="radio" name="radio" id="repair" onchange="radio()" />
<span class="note">"Repair" option is checked</span>
</label>
javaScript:
<script>
function radio() {
var myRadio = document.querySelectorAll('input[name="radio"]'); // get radio
var myNotes = document.querySelectorAll('.note'); // get notes
if (myRadio[0].checked === true) { // if the first radio checked
myNotes[0].style.display = 'inline-block'; // show first note
myNotes[1].style.display = 'none'; // hide the second
}
else { // if not do the apposite
myNotes[0].style.display = 'none';
myNotes[1].style.display = 'inline-block';
}
}
</script>
Hope it help you!

Related

Hide a div if Gravity form results return nothing

I have a Gravity form which is being used as an assessment. Users click checkboxes that are relevant to them and the confirmation page shows different groups they qualify for (due to the checkboxes that clicked).
If a group doesn't have any of its boxes checked, it won't appear on the submission page (the result is hidden).
I'm trying to also hide a div from appearing if XYZ group doesn't appear. For example, if result1 didn't have anything checked, I want to hide div id "myid".
I've been trialling and erroring in how to get this done with php but am still learning the language and feeling a bit lost. I found the JS code below and thought it could be a good indication of what I'm trying to achieve. I just don't know how to exactly get it.
if($result111 = '') {
document.getElementById("myid").style.display = 'none';
}
else
{
document.getElementById("myid").style.display = 'inline';
}
I have created an example of the task you described:
<html>
<head>
<title>Hide div</title>
</head>
<body>
<input type="checkbox" id="choice1" name="choice1" value="1" onclick="choiceEvent()"> Choice 1 <br>
<input type="checkbox" id="choice2" name="choice2" value="1" onclick="choiceEvent()"> Choice 2 <br>
<input type="checkbox" id="choice3" name="choice3" value="1" onclick="choiceEvent()"> Choice 3 <br>
<div id="results" style="display:none">
One of the checkboxes is pressed.
</div>
<script>
function choiceEvent(){
var choice1 = document.getElementById('choice1');
var choice2 = document.getElementById('choice2');
var choice3 = document.getElementById('choice3');
if(choice1.checked || choice2.checked || choice3.checked){
document.getElementById('results').style.display = 'block';
} else {
document.getElementById('results').style.display = 'none';
}
}
</script>
</body>
</html>
I hope it helps.

HTML div not disappearing after input is removed

Basically what I'm trying to do is conditionally show a section of a form. If an input field has either nothing or 0 as inputted, the section is hidden. Otherwise, I want the section to be displayed. While the section does appear when I input numbers in the correct field, it doesn't disappear after I remove the input.
So far, I've tried changing the event listener to listen to the busmiles variable after moving it outside of the function, but that results in the the section never displaying. I'm not sure what's causing this problem either since I'm not very experience in javascript.
HTML file
<label for="weeklybus">On average, how many miles do you take the bus/train in a week?</label><br>
<input name="weeklybus" id="weeklybus" type="number" required>
<br id="oppositeform">
<div id="busmodeform">
<p>Do you typically take the bus, light rail, or heavy rail?</p>
<input name="busmode" id="bus" type="radio" value="bus">
<label for="bus">Bus</label><br>
<input name="busmode" id="light" type="radio" value="light">
<label for="light">Light rail</label><br>
<input name="busmode" id="heavy" type="radio" value="heavy">
<label for="heavy">Heavy rail</label><br>
</div>
Javascript
function showFormSection() {
var busmiles = document.getElementById('weeklybus').value;
const busmode = document.getElementById('busmodeform');
const extralinebreak = document.getElementById('oppositeform');
if (busmiles != "" && busmiles != "0") {
busmode.style.display = 'block';
extralinebreak.style.display = 'hidden';
} else if (busmiles == "") {
busmode.style.display = 'hidden';
extralinebreak.style.display = 'block';
}
}
window.addEventListener('input', showFormSection);
EDIT: Fixed. Changed from hidden --> none.
You have not declared a "style=" attribute in your DIV element.
Too the DIV style should have a property set for "visibility".
<script>
// goes in head
function hideDiv(){
document.getElementById("busmodeform").style.visibility="hidden";
}
</script>
<div id="busmodeform" onblur="hideDiv();" style="visibility:visible;">

How to display a radio button selected using a variable?

I have a variable that contains a radio button value. I check some conditions, and based on this value the radio button will be selected.
if(cheque_date == system_date) {
cheque_value='Current';
}
else {
cheque_value='PDC';
}
cheque_value = $('input[name=cheque_type]:checked').val();
Radio button:
<label class="radio">
<input type="radio" name="cheque_type" value="Current" />Current
</label>
<label class="radio">
<input type="radio" name="cheque_type" value="PDC" />PDC
</label>
Is this right?
You can check radio button based on value like following.
if(cheque_date == system_date) {
cheque_value='Current';
}
else {
cheque_value='PDC';
}
$('input[name=cheque_type][value="'+cheque_value+'"]').prop('checked', true);
You need some modifications in your code:
1) Add ids to your checkboxes. In HTML, id attribute is unique, so selecting elements with id is much more faster than by classes or tags.
2) Get id in a variable and use that runtime variable in jQuery.
Final code:
<label class="radio">
<input type="radio" name="cheque_type" value="Current" value="Current"/>Current</label>
<label class="radio">
<input type="radio" name="cheque_type" value="PDC" value="PDC" />PDC</label>
AND jQuery code:
var cheque_id = (cheque_date == system_date) ? 'Current' : 'PDC';
cheque_value = $('#'+cheque_type+':checked').val();
Can you try the code below ?
if(cheque_date == system_date)
cheque_value = 'Current';
} else {
cheque_value = 'PDC';
}
$("input[name='cheque_type'][value='"+cheque_value+"']").prop("checked",true);
var inputValue = $("input[name='cheque_type']:checked").val();
Hope this helps.
Edit: triggering not solves the value issue and I improved my answer and you can see demo of solution on link JSFiddle Demo

Condtionally disable button by Radio and Checkbox

I would like to conditionally disable a button based on a radio and checkbox combination. The radio will have two options, the first is checked by default. If the user selects the second option then I would like to disable a button until at least one checkbox has been checked.
I have searched at length on CodePen and Stack Overflow but cannot find a solution that works with my conditionals. The results I did find were close but I couldn't adapt them to my needs as I am a Javascript novice.
I am using JQuery, if that helps.
If needed:
http://codepen.io/traceofwind/pen/EVNxZj
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
(Please excuse the code, it is in short hand for example!)
The form element IDs are somewhat fixed. The IDs are generated by OpenCart so I believe the naming convention is set by group, rather than unique. I cannot use IDs such as radio_ID_1 and radio_ID_2, for example; this is an OpenCart framework facet and not a personal choice.
Finally, in pseudo code I am hoping someone can suggest a JQuery / javascript solution along the lines of:
if radio = '2' then
if checkboxes = unchecked then
btn = disabled
else
btn = enabled
end if
end if
Here is a quick solution and I hope that's what you were after.
$(function() {
var $form = $("#form1");
var $btn = $form.find("#btn");
var $radios = $form.find(":radio");
var $checks = $form.find(":checkbox[name='optionals']");
$radios.add($checks).on("change", function() {
var radioVal = $radios.filter(":checked").val();
$btn.prop("disabled", true);
if (radioVal == 2) {
$btn.prop("disabled", !$checks.filter(":checked").length >= 1);
} else {
$btn.prop("disabled", !radioVal);
}
});
});
Here is a demo with the above + your HTML.
Note: Remove all the IDs except the form ID, button ID (since they're used in the demo) as you can't have duplicate IDs in an HTML document. an ID is meant to identify a unique piece of content. If the idea is to style those elements, then use classes.
If you foresee a lot of JavaScript development in your future, then I would highly recommend the JavaScript courses made available by Udacity. Although the full course content is only available for a fee, the most important part of the course materials--the videos and integrated questions--are free.
However, if you don't plan to do a lot of JavaScript development in the future and just need a quick solution so you can move on, here's how to accomplish what you are trying to accomplish:
$(document).ready(function(){
$('form').on('click', 'input[type="radio"]', function(){
conditionallyToggleButton();
});
$('form').on('click', 'input[type="checkbox"]', function(){
conditionallyToggleButton();
});
});
function conditionallyToggleButton()
{
if (shouldDisableButton())
{
disableButton();
}
else
{
enableButton();
}
}
function shouldDisableButton()
{
if ($('div#input-option1 input:checked').val() == 2
&& !$('form input[type="checkbox"]:checked').length)
{
return true;
}
return false;
}
function disableButton()
{
$('button').prop('disabled', true);
}
function enableButton()
{
$('button').prop('disabled', false);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<div id="input-option1">First option: (required)
<input type="radio" name="required" id="required" value="1" checked="checked">Yes
<input type="radio" name="required" id="required" value="2">No
<div>
<div id="input-option2">Optionals:
<input type="checkbox" name="optionals" id="optionals" value="2a">Optional 1
<input type="checkbox" name="optionals" id="optionals" value="2b">Optional 2
<div>
<div id="input-option3">Extras:
<input type="checkbox" name="extra" id="extra" value="3">Extra 1
<div>
<button type="button" id="btn">Add to Cart</button>
</form>
Note that the JavaScript code above is a quick-and-dirty solution. To do it right, you would probably want to create a JavaScript class representing the add to cart form that manages the behavior of the form elements and which caches the jQuery-wrapped form elements in properties.

Control Radio Buttons with a Checkbox

I'm using a CMS that hides form elements behind tags, because of some system quirks I've had to set up a checkbox that controls the radio buttons so if the checkbox is ticked the "yes" radio button is selected if not the "no" is selected. I also want the radio buttons to have option "no" checked by default but I don't have control over the line of code for the radio buttons.
I found some Javascript that does a small part of this but I want to integrate it into the jQuery that displays and hides content when the box is ticked.
Here's what I have so far:
$('#checkbox1').change(function() {
$('#content1').toggle("slow");
});
The Javascript I have is this:
function ticked(){
var ischecked = document.getElementById("checkbox").checked;
var collection = document.getElementById("hideradio").getElementsByTagName('INPUT');
if(ischecked){collection[0].checked = true;}else{collection[0].checked = false;}
}
Can you please help write a version of the Javascript but integrate with my jQuery?
Thanks,
You can try this, I assume your html as like this.
<input type="checkbox" id="checkbox1" /> Check Box
<div id="content1" >
Some Content <br />
Some Content <br />
Some Content <br />
Some Content
</div>
<div id="hideradio">
<input type="radio" name="rgroup" value="yes" /> Yes
<input type="radio" name="rgroup" value="no" /> No
</div>
JQuery
$(function(){
$('#hideradio input[type=radio][value=no]').attr('checked',true);
$('#content1').hide();
});
$('#checkbox1').on('change', function() {
$('#content1').toggle("slow");
var self = this;
if(self.checked)
$('#hideradio input[type=radio][value=yes]').attr('checked',true);
else
$('#hideradio input[type=radio][value=no]').attr('checked',true);
});
A Quick DEMO
Try this code
​
$(function(){
$('#checkbox1').on('click' , function() {
var isChecked = $(this).is(':checked');
if(isChecked){
$('#radio1').attr('checked' , true);
$('#content1').toggle("slow");
}
else{
$('#radio1').attr('checked' , false);
}
});
});​
Check [FIDDLE]
If I don't understand correctly then let me know.
I don't know your HTML code so I provide one
<form>
<input type="checkbox" name="test_ck" id="test_ck" />
<br/>
<input type="radio" name="test_radio" id="test_radio" />
</form>
<div id="content"> A content !!! </div>
and javascript jquery
$(function(){
$("#test_ck").on("change", function(){
$("#test_radio").prop("checked", $(this).is(":checked"));
$("#content").toggle("slow");
});
});
Example -> jsfiddle
UPDATED jsfiddle
http://jsfiddle.net/6wQxw/2/
jsfiddle
$(document).on('change', '#checkbox', function() { toggle(this); });
var toggle = function(obj) {
var checked = $(obj || '#checkbox').is(':checked');
$(':radio[value=no]').prop('checked', !checked);
$(':radio[value=yes]').prop('checked', checked);
$('#content').toggle(checked);
}
toggle();
This is a pure JavaScript solution, no need to use jQuery:
<body>
<label for="a">Male</label>
<input type="radio" id="a">
<br/>
<label for="b">Female</label>
<input type="radio" id="b">
<script type="text/javascript">
var nodes = document.querySelectorAll("input[type=radio]");// get elements
var arr = Array.prototype.slice.call(nodes); // convert nodes to array for use in forEach
arr.forEach(function(obj){
obj.addEventListener("change",function(e){
arr.forEach(function(obj){
obj.checked = false;//make other radio false
});
this.checked = true;// make this radio ture
});
});
</script>
</body>

Categories