Can't get .removeChild to work on newly dynamically created div - javascript

I'm attempting to make a remove button for my dynamically created input boxes, however I can't seem to get it to work. I get the feeling its because the "child" didn't exist upon initially loading the script, but I'm not sure.
Any help would be appreciated. Thanks.
var addButton = document.getElementById("add-button");
var removeButton = document.getElementById("remove-button");
var incomeSection = document.getElementById("income");
var incomeRow = document.getElementById("income-row");
var itemCounter = 2
incomeSection.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.id == "add-button") {
incomeSection.innerHTML += '<div id="income-row"><input class="input" type="text" name="income-type-1" placeholder="Income source ' + itemCounter + '"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="remove-button" class="button" type="button" value="-"></div>';
itemCounter++;
}
if (e.target.id == "remove-button") {
incomeSection.removeChild(incomeRow);
}
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#income {
padding: 10px;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
.button {
width: 25px;
height: 25px;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
<div id="income">
<div id="income-displayed">
<h2>Income: <span></span></h2>
</div>
<div id="income-row">
<input class="input" type="text" name="income-type-1" placeholder="Income source">
<span class="currency">£</span>
<input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount">
<input id="add-button" class="button" type="button" value="+">
</div>
</div>

Just replace the following line it will resolved your issue :-
incomeSection.removeChild(incomeRow);
with the following
e.target.parentNode.remove();
var addButton = document.getElementById("add-button");
var removeButton = document.getElementById("remove-button");
var incomeSection = document.getElementById("income");
var incomeRow = document.getElementById("income-row");
var itemCounter = 2
incomeSection.addEventListener("click", activateItem);
function activateItem(e) {
if (e.target.id == "add-button") {
incomeSection.innerHTML += '<div id="income-row"><input class="input" type="text" name="income-type-1" placeholder="Income source '+itemCounter+'"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="remove-button" class="button" type="button" value="-"></div>'; itemCounter ++;
}
if (e.target.id == "remove-button") {
e.target.parentNode.remove();
}
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#income {
padding: 10px;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
.button {
width: 25px;
height: 25px;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
<div id="income">
<div id="income-displayed"><h2>Income: <span></span></h2></div>
<div id="income-row">
<input class="input" type="text" name="income-type-1" placeholder="Income source"><span class="currency">£</span><input class="input income-amount" type="text" name="income-amount-1" placeholder="Amount"><input id="add-button" class="button" type="button" value="+"></div>
</div>

This Snippet demonstrates how to add and remove elements to and from the DOM utilizing:
cloneNode
.children
parentNode
Further details are commented in the source
SNIPPET
// #incFormA element will bind with eventListener
var form = document.getElementById("incFormA");
// #setA will contain the #dupes
var set = document.getElementById("setA");
// Reference to clone template #dupe
var dupe = document.getElementById('dupe');
// Increment counter that will ensure unique ids
var cntr = 0;
// If any part of the form is clicked call actDeact
form.addEventListener("click", actDeact);
/*
| actDeact()
| -If the clicked button's id === addA
| then clone #dupe and add an id (#dupe+cntr)
| -Iterate through it's children
| and assign unique ids and names to
| the 1st and 3rd children of (#dupe+cntr)
| -Append #dupe+cntr to #setA
*/
/*
| -If the clicked button was a .remA
| find it's parentNode and remove it.
*/
function actDeact(e) {
cntr++;
if (e.target.id === 'addA') {
var clone = dupe.cloneNode(true);
clone.id = 'dupe' + cntr;
var i;
var grp = clone.children;
var qty = grp.length;
for (i = 0; i < qty; i++) {
switch (i) {
case 0:
grp[0].id = 'inc' + cntr;
grp[0].name = 'inc' + cntr;
break;
case 2:
grp[2].id = 'amt' + cntr;
grp[2].name = 'amt' + cntr;
break;
default:
break;
}
}
setA.appendChild(clone);
} else if (e.target.className === "remA") {
var clone = e.target.parentNode;
setA.removeChild(clone);
} else return false;
}
html body {
background-color: #c9c9c9;
font-family: 'Montserrat', sans-serif;
color: #686868;
}
#setA {
padding: 10px;
}
/* The clone template is out of the way
| yet still accessible for cloning.
*/
#dupe {
display: none;
}
.input {
padding: 8px;
font-size: 14px;
margin-right: 10px;
margin-bottom: 5px;
width: 30%;
}
button {
width: 25px;
height: 25px;
float: right;
}
.currency {
padding: 10px;
font-size: 14px;
margin-right: -4px;
margin-bottom: 5px;
background-color: darkgray;
color: white;
}
/*
| This ruleset is for positioning #addA
*/
.block {
position: relative;
display: block;
min-height: 100%;
width: 20%;
left: 80%;
bottom: 15px;
}
<!--Use <form> to post collect and send data*-->
<form id='incFormA' name='incFormA'>
<fieldset id="setA">
<legend class="display">
<!--Use <output> to calculate and display data*-->
<h2>Income: <output id='outA'></output></h2>
</legend>
<div class='block'>
<!--One add <button>-->
<button id="addA" type='button'>+</button>
</div>
<!--#dupe is the group of elements kept as a clone template-->
<span id='dupe'>
<input id='inc' class="input" name="inc" type="text" placeholder="Income source">
<span class="currency">£</span>
<input id="amt" class="input" name="amt" type="text" placeholder="Amount">
<button class="remA">-</button>
</span>
</fieldset>
</form>
<!--*Choice of elements optional-->

Related

HTML Number Input: Only Allow Arrow Buttons

Here is what I mean:
Is it possible to only allow input via clicking the arrow buttons, and NOT from actually typing?
Ie: I could not type in "11", but if I click the up arrow 11 times then it will go to 11?
Here is my input field right now:
<input type="number" min="00" max ="99" id="timer02_min"
maxlength="2" value="00">
Is there some native way of doing this? Or should I look more into buttons and some styling?
Use event.preventDefault() in keydown event;
// no keyboard
document.getElementById("timer02_min").addEventListener("keydown", e => e.preventDefault());
// allow up/down keyboard cursor buttons
document.getElementById("timer02_min2").addEventListener("keydown", e => e.keyCode != 38 && e.keyCode != 40 && e.preventDefault());
no keyboard:
<input type="number" min="00" max ="99" id="timer02_min"
maxlength="2" value="00">
<br>
with up/down cursor keys:
<input type="number" min="00" max ="99" id="timer02_min2"
maxlength="2" value="00">
function change(n){
var num = document.getElementById("num");
var number1 = num.innerHTML;
var number = Number(number1);
var num2 = number.toString();
if(n == "s"){
}else{
number = number+n;
}
if(number <= 0){
number = 0;
}
if(number > 99){
number = 99;
}
if(num2.length == 1){
var num1 = number;
number = "0"+num1;
}
document.getElementById("num").innerHTML = number;
}
change("s");
.input{
border-style: solid;
border-color: gray;
border-width: 1px;
border-radius: 2px;
padding: 1px;
height: 26px;
width: 40px;
text-align: left;
position: relative;
padding-left: 10px;
}
.spinner-button {
position: absolute;
top: 0px;
right: 0px;
}
#inc-button{
padding-top: 3.5px;
background-color: #ccc;
width: 14.5px;
text-align: center;
margin-bottom: 1px;
height: 10px;
line-height: 10px;
cursor: pointer;
border: none;
user-select: none; /* Standard */
}
#dec-button{
cursor: pointer;
padding-top: 3px;
background-color: #ccc;
width: 14.5px;
text-align: center;
margin: 0px;
height: 10px;
line-height: 10px;
border: none;
user-select: none; /* Standard */
}
#inc-button:hover,#dec-button:hover{
background-color: #b5b5b5;
}
<div id="timer02_min" class="input">
<div id="num">00</div>
<div class="spinner-button">
<div onclick="change(1);" id="inc-button">+</div>
<div onclick="change(-1);" id="dec-button">-</div>
</div>
</div>
Try This!
The Number you want to start put it in the #num div.

When to Call JavaScript Toggle Function?

I have a drop down menu I need to make appear and disappear using pure JavaScript (no libraries/jQuery). Thus I am developing a toggle function. However despite trying several approaches, nothing seems to work. My current idea is to create a variable to hold the state of the menu (open or closed). Once the display of the menu changes from "none" to "block", the variable should change from "closed" to "open". Then an event listener would be added to the body element so when anything is clicked, the menu closes (i.e. the display property is changed back to "none").
Unfortunately the above doesn't seem work. When I put the If/else block outside of an event listener it fires when the page loads, but not when the menuToggle variable changes. If I put it or a function inside the menuPlaceholder event listener the menu won't open, probably due to the open and close code being called basically at the same time.
Clearly I am missing something, probably related to program control or function calling. Does anyone have any insights?
The code I am working with is below. Note the alert functions peppered throughout the code are for testing purposes only.
//Puts IDs for search preference selection box into variables
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
//Puts IDs for text input box and submission into variables
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
//Adds class to each search option and puts ID of hidde field into variable
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
//Global variable to indicate whether searchOptions menu is opened or closed
var menuToggle = "closed";
//Closes element when one clicks outside of it.
function hideOnClickOutside(element) {
const outsideClickListener = event => {
if (!element.contains(event.target) && isVisible(element)) { // or use: event.target.closest(selector) === null
element.style.display = 'none'
removeClickListener()
}
}
const removeClickListener = () => {
document.removeEventListener('click', outsideClickListener)
}
document.addEventListener('click', outsideClickListener)
}
const isVisible = elem => !!elem && !!( elem.offsetWidth || elem.offsetHeight || elem.getClientRects().length )
//When the placeholder box is clicked, the option menu appears
menuPlaceholder.addEventListener('click', function (event){
menuDisplay.style.display = "block";
menuToggle = "open";
//Add click event to searchPref buttons
for (i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value=this.value;
boxLabel.innerHTML = this.value;
menuDisplay.style.display = "none";
menuPlaceholder.style.display = "inline-block";
});
}
});
//This code causes the text input box of the search form to appear when the background box is clicked
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
//hideOnClickOutside(menuDisplay);
});
if (menuToggle == "open"){
document.body.addEventListener('click', function(event){
alert('Foo!');
})
}else{
alert('Boo!');
}
/*function toggleMenu () {
//menuDisplay.style.display = "none";
alert('Boo!');
menuToggle = "closed";
}*/
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection"><span id="searchLabel">Catalog</span><img src="down.png" height="30px" width="30px" /></div>
<div id="searchOptions">
<ul>
<li><button type="button" name="searchPref" value="Catalog" class="buttonSearch">Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span></button></li>
<li><button type="button" name="searchPref" value="SearchMore" class="buttonSearch">SearchMore<br /><br /><span class="searchSubHeading">Search everything</span></button></li>
<li><button type="button" name="searchPref" value="Journals" class="buttonSearch">Journals<br /><br /><span class="searchSubHeading">Search journals</span></button></li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/><button type="submit" id="submit"></button></div>
<div id="otherLinks">Advanced Catalog Search | WorldCat | eBooks</div>
</form>
Some issues:
Adding event listeners within an event listener is in most cases a code smell: this will add those inner listeners each time the outer event is triggered. Those listeners remain attached, and so they accumulate. So, attach all event handlers in the top-level script, i.e. on page load, and then never again.
The if ... else at the end will execute on page load, and then never again. So the value of menuToggle is guaranteed to be "closed". You need to put that if...else switch inside the handler, so that it executes every time the event triggers, at which time the menuToggle variable will possibly have a modified value.
The body element does not stretch (by default) over the whole window. If you want to detect a click anywhere on the page, you should attach the listener on the document element itself, not on document.body.
When the click on the menu placeholder is handled, you should avoid that this event "bubbles" up the DOM tree up to the document, because there you have the other handler that wants to hide the menu again. You can do this with event.stopPropagation().
The global variable is not absolutely necessary, but if you use it, then I would call it menuVisible and give it a boolean value: false at first, and possibly true later.
For actually toggling the menu, I would create a function, which takes the desired visibility (false or true) as argument, and then performs the toggle.
Do not use undeclared variables, like the for loop variable i. Define it with let.
Here is your code with those changes implemented. Of course, there is still a lot that could be improved, but I believe that goes beyond the scope of this question:
var menuPlaceholder = document.getElementById('searchSelection');
var menuDisplay = document.getElementById('searchOptions');
var boxLabel = document.getElementById('searchLabel');
var searchBoxPlaceholder = document.getElementById('searchInput');
var searchInput = document.getElementById('searchBox');
var submitButton = document.getElementById('submit');
var searchPrefSubmission = document.getElementsByClassName('buttonSearch');
var hiddenInput = document.getElementById('searchChoice');
// Changed name and type of global variable:
var menuVisible = false;
// Removed some functions ...
menuPlaceholder.addEventListener('click', function (event){
// Use new function for actually setting the visibility
toggleMenu(!menuVisible);
// Avoid that click event bubbles up to the document level
event.stopPropagation();
});
// Add these event handlers on page load, not within another handler
// Define loop variable with let
for (let i = 0; i < searchPrefSubmission.length; i++) {
//Assigns value of the button to both the hidden input field and the placeholder box
searchPrefSubmission[i].addEventListener('click', function(event) {
hiddenInput.value = this.value;
boxLabel.innerHTML = this.value;
// Use the new function for setting the visibility
toggleMenu(false);
menuPlaceholder.style.display = "inline-block";
});
}
searchBoxPlaceholder.addEventListener('click', function(event){
searchInput.style.display = "inline";
submitButton.style.display = "inline";
});
// Bind handler on document itself, and call new function
document.addEventListener('click', function(event) {
toggleMenu(false);
});
// new function to perform the toggle
function toggleMenu(show) {
menuDisplay.style.display = show ? "block" : "none";
menuVisible = show;
}
body {
font-family:Montserrat, sans-serif;
}
#searchOptionPlaceholder {
display: inline-block;
}
#searchSelection {
padding: 10px 20px;
margin-right: 10px;
background-color: #F0F3F5;
display: inline-block;
color: #000000;
width: 140px;
max-width: 200px;
max-height: 35px;
border: 2px solid black;
vertical-align: middle;
}
#searchSelection img {
float: right;
}
#searchLabel {
display: inline-block;
padding-top: 10px;
vertical-align: top;
}
#searchOptions {
display: none;
background-color: #F0F3F5;
position: absolute;
z-index: 2;
}
#searchOptions ul {
background-color: #F0F3F5;
padding: 5px;
}
#searchOptions li {
list-style-type: none;
border-bottom: 2px solid black;
}
#searchOptions li:hover {
background-color: #706868;
color: #ffffff;
}
.buttonSearch {
background-color: transparent;
border: none;
padding: 10px;
font-size: 14px;
}
.searchSubHeading {
font-size: 12px;
}
#searchInput {
display: inline-block;
background-color: #F0F3F5;
padding: 10px 100px;
position: relative;
top: 0px;
max-width: 350px;
border: 2px solid black;
vertical-align: middle;
}
#searchInput img {
position: relative;
left: 80px;
}
#searchBox {
display: none;
width: 80%;
background-color: #F0F3F5;
border: none;
font-size: 1.5em;
position: relative;
right: 50px;
vertical-align: middle;
}
#submit {
border: none;
background-image: url('https://library.domains.skidmore.edu/search/magnifyingGlass.png');
background-repeat: no-repeat;
background-size: contain;
width: 50px;
height: 30px;
position: relative;
right: -80px;
vertical-align: middle;
}
#otherLinks {
margin-top: 10px;
}
#otherLinks a{
color: #000000;
}
#otherLinks a:hover{
color: #006a52;
}
<h1>Library Search</h1>
<form method="post" action="https://library.domains.skidmore.edu/search/searchBox.php" id="librarySearch">
<div id="searchSelection">
<span id="searchLabel">Catalog</span>
<img src="down.png" height="30px" width="30px" />
</div>
<div id="searchOptions">
<ul>
<li>
<button type="button" name="searchPref" value="Catalog" class="buttonSearch">
Catalog<br /><br /><span class="searchSubHeading">Search books and DVDs</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="SearchMore" class="buttonSearch">
SearchMore<br /><br /><span class="searchSubHeading">Search everything</span>
</button>
</li>
<li>
<button type="button" name="searchPref" value="Journals" class="buttonSearch">
Journals<br /><br /><span class="searchSubHeading">Search journals</span>
</button>
</li>
</ul>
</div>
<div id="searchInput">
<input type="hidden" id="searchChoice" name="searchPref" value="catalog" />
<input type="search" id="searchBox" size="60" name="searchText" placeholder="Search our holdings"/>
<button type="submit" id="submit"></button>
</div>
<div id="otherLinks">
Advanced Catalog Search |
WorldCat |
eBooks
</div>
</form>

How to position a h1 directly over an input and have it be for all screens?

So I want to replace the text inside of an input field with a h1 tag as soon as the user hits submit because i want the text to have an animation but i can't animate the text inside the text field.
I linked the code pen project version of it to make it easier then organizing all the code in here. I added all the code I had so I wouldn't leave anything out although some of it may be irrelevant.
Basically I want the h1 tag to appear exactly where the input text was so it looks like nothing ever got replaced.
https://codepen.io/timvancowabunga/pen/rNOqdYd
$(document).ready(function() {
$('#btn1').click(function() {
$('#test').text($("#message").val());
$('#message').val('');
$('#test').val('');
});
});
function onTextClick() {
document.getElementById('btn1').className = "show";
}
function showButton() {
document.getElementById('btn1').style.display = 'block';
}
function showSendButton() {
document.getElementById('btn2').style.display = 'block';
}
function formCheck() {
var input = $('#message').val();
if (input == '') {
alert("Please Submit a Valid Message");
} else {
hideButton();
showSendButton();
}
}
function hideButton() {
document.getElementById('btn1').style.display = 'none';
}
function hideSendButton() {
document.getElementById('btn2').style.display = 'none';
document.getElementById('sent').style.display = 'block';
}
function myMove() {
var textWrapper = document.querySelector('.ml13');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
anime.timeline()
.add({
targets: '.ml13 .letter',
translateY: [0, -1600],
opacity: [1, 0],
easing: "easeInSine",
duration: 3600,
delay: (el, i) => 800 + 60 * i
});
}
body {
background-color: #368670;
font-family: sans-serif;
}
.ml13,
.ml14,
.ml15 {
font-size: 1.9em;
text-transform: uppercase;
letter-spacing: 0.2em;
font-weight: 600;
}
.ml15 {
letter-spacing: 0em;
text-align: center;
}
.ml13 .letter {
display: inline-block;
line-height: 1em;
}
.line {
display: flex;
margin: auto;
width: 50%;
margin-top: 500px;
}
.wrappy {
position: relative;
}
.wrappy h1 {
position: absolute;
left: 48.5%;
top: 20%
}
.butt {
padding-top: 50px;
display: flex;
margin: 0 auto;
width: 100%;
}
#btn1,
#btn2 {
display: table;
margin: 0 auto;
}
input {
z-index: 1000;
margin-left: 10%;
width: 80%;
background: transparent;
border: 0;
border-bottom: 1px solid;
padding: 1em 0 .1em;
text-align: center;
font-size: 18px;
font-family: inherit;
font-weight: 300;
line-height: 1.5;
color: inherit;
outline: none;
}
input:focus {
border-color: #ffffff;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>
<div class="truth">
<!-- <div class="line"> -->
<div class="message-box">
<form class="message-form">
<h2 class="ml15" for="message">TELL A TRUTH</h2>
<div class="wrappy">
<input type="text" id="message" name="message" autocomplete="off" class="ml14">
<!-- <h1 id="test" class="ml13">I love your music!</h1> -->
<h1 id="test" class="ml13"></h1>
</div>
</form>
</div>
<div class="butt">
<button id="btn1" onclick="formCheck();">Ready to Send?</button>
<button id="btn2" style="display: none" onclick="myMove(); setTimeout(showButton, 3000); hideSendButton();">Send!</button>
</div>
</div>
You want to put H1 below the input.
Then you make the text input transparent. Bind the input value to h1.
So in effect when user clicks and type, they are selecting the input and changing its value, but it's transparent, to be shown by the h1 below the input that you will eventually animate.
Also because you mentioned you want it to display correctly in all platforms. You then have to be cognisant of the default behaviours of DOM and CSS properties. If you alter them to get what you want without knowing its natural order, you can get unexpected behaviour and reduce cross-browser compatibility. I have made changes to reflect that.
$(document).ready(function () {
$("#btn1").click(function () {
$("#test").text($("#message").val());
$("#message").val("");
$("#test").val("");
});
});
function onTextClick() {
document.getElementById("btn1").className = "show";
}
function showButton() {
document.getElementById("btn1").style.display = "block";
}
function showSendButton() {
document.getElementById("btn2").style.display = "block";
}
function formCheck() {
var input = $("#message").val();
if (input == "") {
alert("Please Submit a Valid Message");
} else {
hideButton();
showSendButton();
}
}
function hideButton() {
document.getElementById("btn1").style.display = "none";
}
function hideSendButton() {
document.getElementById("btn2").style.display = "none";
document.getElementById("sent").style.display = "block";
}
// attach this to bind h1 to the input value at all times.
$("#message").keyup(function () {
var self = this;
$("#test").text($(this).val());
});
function myMove() {
var textWrapper = document.querySelector(".ml13");
textWrapper.innerHTML = textWrapper.textContent.replace(
/\S/g,
"<span class='letter'>$&</span>"
);
anime.timeline().add({
targets: ".ml13 .letter",
translateY: [0, -1600],
opacity: [1, 0],
easing: "easeInSine",
duration: 3600,
delay: (el, i) => 800 + 60 * i
});
}
body {
background-color: #368670;
font-family: sans-serif;
}
.ml13,
.ml14,
.ml15 {
font-size: 1.9em;
text-transform: uppercase;
letter-spacing: 0.2em;
font-weight: 600;
}
.ml15 {
letter-spacing: 0em;
text-align: center;
}
.ml13 .letter {
display: inline-block;
line-height: 1em;
}
.line {
display: flex;
margin: auto;
width: 50%;
margin-top: 500px;
}
.wrappy {
position: relative;
text-align: center;
}
.wrappy h1 {
position: absolute; /* you then want to give wrappy h1 this to make it occupy no space. */
width: 100%; /* to centralize the text, your option here is to make this 100% width and use text-align */
text-align: center;
padding-top: 21px;
}
.butt {
padding-top: 50px;
display: flex;
margin: 0 auto;
width: 100%;
}
#btn1,
#btn2 {
display: table;
margin: 0 auto;
}
input {
position: relative; /* in order for z-index to work, you need to give an element `position` attribute of value `static`, `relative` or `absolute`. */
z-index: 1000; /* now this will work. wrappy h1 is not given a `z-index` so it defaults to `1`, hence input will be on top of wrappy h1 now. */
width: 80%;
background: transparent;
border: 0;
border-bottom: 1px solid #000; /* you need the line back because we are going to assign color to be transparent */
padding: 35px 0 0 0;
text-align: center;
font-size: 18px;
font-family: inherit;
font-weight: 300;
line-height: 1.5;
color: transparent; /* make the text transparent */
outline: none;
}
input:focus {
border-color: #ffffff;
}
<div class="truth">
<!-- <div class="line"> -->
<div class="message-box">
<form class="message-form">
<h2 class="ml15" for="message">TELL A TRUTH</h2>
<div class="wrappy">
<!-- for natural flow, you want to shift #test to above the input, so that input can stack on top of it -->
<h1 id="test" class="ml13"></h1>
<input type="text" id="message" name="message" autocomplete="off" class="ml14">
<!-- <h1 id="test" class="ml13">I love your music!</h1> -->
</div>
</form>
</div>
<div class="butt">
<button id="btn1" onclick="formCheck();">Ready to Send?</button>
<button id="btn2" style="display: none" onclick="myMove(); setTimeout(showButton, 3000); hideSendButton();">Send!</button>
</div>
</div>

How to display the value of a "number type input" in a span next to it

I have a number input type element. I want its value to be displayed in the span next to it. As I click or scroll on the increase or decrease button inside the input. I want the span's relative value to change. Is it possible??
I have tried to get the value and display in span but did not worked.
Javascript
var displayer = document.getElementById('displayer');
var day = document.getElementById('days');
var hrs = document.getElementById('hours');
var s_t = document.getElementById('s_t');
function funcday() {
day.style.border = "1.5px solid darkorange";
hrs.style.border = "1.5px solid mediumaquamarine";
s_t.style.border = "1.5px solid darkorange";
s_t.setAttribute("max", 365);
var d = s_t.value;
document.getElementById('display_d').textContent = d;
}
function funhrs() {
day.style.border = "1.5px solid mediumaquamarine";
hrs.style.border = "1.5px solid darkorange";
s_t.style.border = "1.5px solid darkorange";
s_t.setAttribute("max", 48);
var h = s_t.value;
document.getElementById('display_h').textContent = h;
}
#container {
display: flex;
}
.st {
width: 60px;
margin-right: 10px;
}
#days,
#hours {
color: #fff;
width: 70px;
margin-left: 10px;
padding: 6px;
cursor: pointer;
background-color: mediumaquamarine;
border: 1.5px solid mediumaquamarine;
text-align: center;
font-family: 'Courier';
}
.displayer {
align-content: center;
text-align: center;
line-height: 2;
margin-left: 20px;
margin-right: 20px;
font-size: 15px;
border: 1px solid white;
display: block;
float: right;
}
.displayer span {
margin-right: 5px;
margin-left: 5px;
}
<div id="container">
<input type="number" min="1" class="st" id="s_t" autocomplete="off">
<div id="days" onclick="funcday();">Days</div>
<div id="hours" onclick="funhrs();">Hours</div>
<div id="displayer" class="displayer">
<span id="display_d">00</span><span>Days</span>
<span id="display_h">00</span><span>Hours</span>
</div>
</div>
You should add onchange event handler to the input element and change text of the span element inside this handler.

Javascript: Focus is not a function

I'm writing a registration form and am trying to sort out some validation. I got this same problem when my validate button was inside the <form> however to fix this I just moved it out as I guessed the button was causing the form to refresh.
However now after inserting multiple if statement into the "ValidateForm()" function this error message has seemed to come back.
Error: Uncaught TypeError: Forename.focus is not a function
at ValidateForm (Login Form Complex.html?Forename=&Surname=&Username=&Password=&Email=:79)
at HTMLButtonElement.onclick (Login Form Complex.html?Forename=&Surname=&Username=&Password=&Email=:63)**
function ValidateForm() {
var Forename = document.getElementById("Forename").value;
var Surname = document.getElementById("Surname").value;
var Username = document.getElementById("Username").value;
var Password = document.getElementById("Password").value;
var Email = document.getElementById("Email").value;
var Errors = 0
if (Forename == "") {
document.LoginForm.Forename.focus();
Forename.focus();
Errors = Errors + 1
}
if (Surname == "") {
document.LoginForm.Forename.focus();
Surname.focus();
Errors = Errors + 1
}
if (Username == "") {
document.LoginForm.Forename.focus();
Username.focus();
Errors = Errors + 1
}
if (Password == "") {
document.LoginForm.Forename.focus();
Password.focus();
Errors = Errors + 1
}
if (Errors != 0) {
alert("Please fill in the highlighted boxes")
return false;
}
}
body {
margin: 0;
padding: 0;
background: url(LoginBack.jpg);
background-size: cover;
background-position: center;
font-family: century gothic;
}
.loginbox {
width: 420px;
height: 680px;
background: #5CDB95;
color: #05386B;
top: 50%;
left: 50%;
position: absolute;
transform: translate(-50%, -50%);
box-sizing: border-box;
padding: 70px 30px;
border-radius: 30px;
}
.avatar {
width: 150px;
height: 150px;
border-radius: 50%;
position: absolute;
top: -75px;
left: calc(50% - 75px);
}
h1 {
margin: 0px;
padding: 0 0 20px;
text-align: center;
font-size: 40px;
}
.loginbox p {
margin: 0;
padding: 0;
font-weight: bold;
}
.loginbox input {
width: 100%;
margin-bottom: 20px;
}
.loginbox input[type="text"],
input[type="password"],
input[type="email"] {
border: none;
border-bottom: 1px solid #05386B;
background: transparent;
outline: none;
height: 40px;
font-size: 20px;
color: #379683;
}
.loginbox button[type="Submit"] {
border: 2px solid #05386B;
background: #379683;
height: 40px;
width: 362px;
font-size: 20px;
color: ;
border-radius: 20px;
}
.loginbox button[type="submit"]:hover {
cursor: pointer;
background: #8EE4AF;
}
.loginbox a {
text-decoration: none;
font-size: 15px;
line-height: 20px;
color: #379683;
}
.loginbox a:hover {
cursor: pointer;
color: #8EE4AF;
}
.loginbox input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus {
border: none;
border-bottom: 1px solid #8B0000;
background: transparent;
outline: none;
height: 40px;
font-size: 20px;
color: #8B0000;
}
<div class="loginbox">
<img src="Logo.jpg" class="avatar">
<h1> Create Account </h1>
<form name="LoginForm">
<p>Forename<p><input type="text" name="Forename" id="Forename" placeholder="Enter Forename here">
<p>Surname<p><input type="text" name="Surname" id="Surname" placeholder="Enter Surname here">
<p>Username<p><input type="text" name="Username" id="Username" placeholder="Enter Username here">
<p>Password<p><input type="password" name="Password" id="Password" placeholder="Enter Password here">
<p>Email<p><input type="email" name="Email" id="Email" placeholder="Enter Email here">
<!--
<p>Gender<p><input type="radio" id="Male" name="Gender" value="Male">Male</input>
<input type="radio" id="Female" name="Gender" value="Female">Female</input>
-->
<button onclick="ButtonSubmit()" type="Submit" value="True" name="ButtonSubmit"> Submit </button><br /><br />
Forgot your password? <br />
Already got an account? <br /><br />
</form>
<button onclick="ValidateForm()"> Validate </button>
</div>
Your Forename variable is not holding a reference to a DOM element. It is referencing the .value of that element. The same is true for all of your other DOM variables.
var Forename = document.getElementById("Forename").value;
The value doesn't have a .focus() method. The element does.
In general, it's best not to set variables to properties of DOM elements because, if you determine later that you need a different DOM property, you have to scan the DOM again for a reference you already scanned for. Additionally, setting variables to the DOM elements themselves, and not properties of the elements, will prevent your error, which is very common.
So, change your variables to be set up like this:
var Forename = document.getElementById("Forename");
And then, when you need the value, you can just write:
Forename.value
And, when you want to use the focus() method, just write:
Forename.focus();
You can access whatever aspect of the element you want if you always start from the element itself.
E.g.Forename var have the value of Forename input element then:
var Forename = document.getElementById("Forename"); //DOM element
var fornameValue = Forename.value //value
Forename.focus() //focus function

Categories

Resources