HTML div not disappearing after input is removed - javascript

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;">

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.

Show/hide on checkbox click does not work consistently

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!

Creating a simple mathematics game

I am new to the javascript developing world and I took it upon myself to create a small game that my fathers students will be able to play at school. This game consists of 4 different mathematical operations (Adding,Subtracting,Multiplication,Division). Once the student clicks on the operation button, they will then be transferred to a new page. This page will have numbers from 1 to 10. This number will be used as a static number. After the user selects this number, they will have 10 different problems to answer. The first number will be a random number from 1 to 12 and the second number will be the digit they selected on the page before. After completing the 10 problems, they will be greeted with a page that will inform them which questions they have missed. I have started the code for the addition part but I ran into several complications.
1) how do i transfer the answer from one function, to another? This will be used to check the input.
2) Will it be more intuitive to use a switch statement in order to select the operation & the static number?
3) Is there any other methods that would facilitate the making of this game?
I would like to thank you in advance and apologize for the long post. I am a bit lost and would love to get some kind of feedback.
var x;
function startAdd() {
var random = new Array();
for (var i = 0; i < 1; i++) {
random.push(Math.floor(Math.random() * 13));
// console.log(random[i]);
}
var allRadioButtons = document.getElementsByName("dif");
var secondNumber;
for (var i in allRadioButtons) {
if (allRadioButtons[i].checked) {
secondNumber = +allRadioButtons[i].value;
break;
}
}
for (var a = 0; a < 1; a++) {
document.getElementById('probFirst').innerHTML = random[a];
document.getElementById('probSecond').innerHTML = secondNumber;
/*
compareUser();
function compareUser(){
if (prob != )
} */
}
}
function myFunction() {
var x = document.getElementById("userNumb").value;
document.getElementById("Answer").innerHTML = x;
}
<title>RicoMath - Addition</title>
<body>
<h1>RicoMath</h1>
<h1 class="add">Addition</h1>
<h2>Difficulty</h2>
<div id="options">
<div>
<input id="num1" type="radio" name="dif" value="1">
<label for="num1">1</label>
</div>
<div>
<input id="num2" type="radio" name="dif" value="2">
<label for="num2">2</label>
</div>
<div>
<input id="num3" type="radio" name="dif" value="3" checked>
<label for="num3">3</label>
</div>
<div>
<input id="num4" type="radio" name="dif" value="4">
<label for="num4">4</label>
</div>
<div>
<input id="num5" type="radio" name="dif" value="5">
<label for="num5">5</label>
</div>
<button onclick="startAdd()">Begin!!!!</button>
<h4 id='probFirst'></h4>
<h4 id='probSecond'></h4>
</div>
<input type="number" id="userNumb" value="">
<button onclick='myFunction()'>Enter UserNumb</button>
<p id="Answer"></p>
</body>
1) To transfer the data to your next "page", the easy option for you would be to have seperate divs for seperate pages in the same html file. Then when you need to go the the "next page", just show the div you need to show and hide the others.
Here's a the html + pure javascript code for that with a working example:
<body>
<div id="page1" style="border-width:2px;border-style:solid">
your first page
<button onclick="showPage2()">Go to Page 2</button>
</div>
<div id="page2" style="border-width:2px;border-style:solid">
2nd page
</div>
<div id="page3">
3rd page
</div>
<script>
showPage1();
function hide(id){
document.getElementById(id).hidden = true;
}
function show(id){
document.getElementById(id).hidden = false;
}
function showPage1(){
show("page1");
hide("page2");
hide("page3");
}
function showPage2(){
show("page2");
hide("page1");
hide("page3");
}
</script>
</body>
Here's a working fiddle.
To transfer your value from the input, just use document.getElementById() since you are in the same html document.
2) To get the selected value from the radio button list, just use (as per your code):
var rates = document.getElementById('options').value;
You can use the same method to get the value from a input box. Please make sure you add a check for empty input and also to check if a radio button has been selected before getting the value.
I don't see any need to loop as you have done.
3) Definitely learn and use jquery. It will make your effort much less.
Hope this helps and happy coding!

Javascript onclick fails to send value while onfocus of text input

If a user clicks the save button as the next action after typing street data the onblur action intercepts the onclick and does not trigger the save. However, if you add some padding (30px) and click above the word save it works but below the word Save it does not work, the same as with no padding. I'm certain users will go right from typing text in the input field then click Save which will fail unless they first click somewhere else and then click Save. I’ve provide html and javascript example below. Is there a way using javascript to solve this issue?
<html>
<script>
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display='';
document.getElementById('street').value='';
}
function blured() {
document.getElementById('title').style.display='none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value='street';
}
}
</script>
<style>
.pad5 { padding:5px; }
.pad30 { padding:30px; }
</style>
<body>
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
</body>
</html>
I converted this to jsfiddle but I'm not doing something right (newbie) https://jsfiddle.net/eyo63mav/26/
use onMouseDown instead of onClick in your save button. Then onMouseDown will be fired before onBlur
below is working code
function showstreet() {
var x = document.getElementById('street').value;
alert(x);
}
function focused() {
document.getElementById('title').style.display = '';
document.getElementById('street').value = '';
}
function blured() {
document.getElementById('title').style.display = 'none';
if (document.getElementById('street').value == '') {
document.getElementById('street').value = 'street';
}
}
<div id="title" class="pad5" style="display:none;">STREET NAME</div>
<div>
<input id="street" type="text" value="street" class="pad5" onfocus="focused()" onblur="blured()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="showstreet()">
</div>
Styling rarely makes a difference with events -- now, while that's a blanket statement and in lots of cases we find the styling of an inline element such as a link or a paragraph becoming problematic with inline events such as OnClick and OnFocus, in your case, adding thirty pixels to the size of a button is not your problem.
The problem with your code is that the variable you're assigning your #title's value to is local (it's inside the scope of showstreet(), of which can only be accessed by aforementioned function) -- nevermind that, it's never used again. You save a value to it, it alerts the user, and that's it -- it's never reassigned nor reused, so while it'll forever stay as the street name they entered, you'll never see it unless you apply it to something.
It took me a while to figure out what exactly you're trying to save, but I think I've managed it.
Here's the code I've created:
var streetValue = "Your street will appear here.";
function clickedField() {
// Init title
document.getElementById('title').innerHTML = streetValue;
// Reset field
document.getElementById('street').value = '';
}
function saveValue() {
// Reassign streetValue
streetValue = document.getElementById('street').value;
// Checking if value was left empty
if (streetValue === '') {
document.getElementById('title').innerHTML = "Error: No Street Entered!";
} else {
document.getElementById('title').innerHTML = streetValue;
}
}
(I'm not entirely sure what you had onblur for, but it should be very easy to insert back. If you need some help with that, comment on my reply, I'll be happy to.)
Now if we update the HTML with the approprate functions:
<div id="title" class="pad5" style="">STREET NAME</div>
<div>
<input id="street" type="text" name="street" value="street" class="pad5"
onfocus="clickedField()">
</div>
<br>
<div>
<input type="button" value="Save" class="pad30" onclick="saveValue()">
</div>

Javascript visibility slow on sub elements

I have used javascript style to imitate a pop-up box(any other idea would be appreciated). I have a function to set it visible or hidden based on some conditions.
I have two buttons on the pop up box ,"close": which closes the popup and sets it as hidden and "save": which saves whatever was on the pop up box.
My function only tells the box to close when i want it to. It does this right. But it takes about 4 seconds for both buttons to be hidden(which is not acceptable). and so i tried to invoke another function that hides both buttons as soon as the box is hidden, but this 4 second interval is still there and i have no idea why.
JAVASCRIPT
function login(showhide) {
if (showhide == "show") {
document.getElementById('popuplogin').style.visibility = "visible";
} else if (showhide == "hide") {
document.getElementById('popuplogin').style.visibility = "hidden";
}
document.getElementById("container1").style.filter = "blur";
}
HTML
<div id ="popuplogin">
<form class ="loginform">
<div class ="backbutton2" onclick="login('hide')"></div>
<input type ="text" placeholder ="Name" id ="loginname" class="boxes" />
<input type="password" placeholder ="Password" id ="loginpassword" class="boxes"/>
<p class ="btn1" onclick ="logger()">LOG IN</p>
</form>
</div>

Categories