Dynamically Removing Inputs / DOM Error - javascript

I've been able to make a section of a form that dynamically adds a tier of inputs on a button click. This new div is appended after the previous div and I am attempting to make a button that can also remove the tier if the user doesn't need it.
My problem is I cannot seem to remove the divs. I can add but not remove. When I look at the DOM I can see when the addDiv button is clicked, it is indeed adding the div and all the content is within the div, so it is being appended properly. But when I try to remove the newly appended div from it's parent element, I get the following error thrown:
addJob.js:18 Uncaught TypeError: Cannot read property 'parentNode' of undefinedremoveJob # addJob.js:18onclick # index.html:1
I'm unsure how to make my removeJob() function defined in a way that is just the reverse of how it was added.
CodePen: http://codepen.io/theodore_steiner/pen/WGEmGr
var i = 0;
function addJob() {
if (i <= 1) {
i++;
var div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_' + i + '"> '+
'<input type="text" class="three-lines" name="position_' + i + '"> '+
'<input type="text" class="three-lines" name="years_' + i + '">'+
'<input type="button" value="-" onclick="removeJob()">';
document.getElementById("employmentHistory").appendChild(div);
}
}
function removeJob(div) {
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
button {
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
}
input[type="button"] {
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
}
input[type="button"]:focus {
outline: none;
}
input.three-lines {
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;
}
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>

You function is right just add the paramter "this" when you put the function in the onclick attribute, like this:
onclick="removeJob(this)"

Well, As per Below discussion passing this in the parameter is the best way to achieve this.
Below is the working code for this-
var i = 0;
var div = null;
function addJob()
{
if(i <= 1)
{
i++;
div = document.createElement("div");
div.innerHTML = '<input type="text" class="three-lines" name="schoolBoard_'+i+'"> <input type="text" class="three-lines" name="position_'+i+'"> <input type="text" class="three-lines" name="years_'+i+'"><input type="button" value="-" onclick="removeJob(this)">';
document.getElementById("employmentHistory").appendChild(div);
}
}
function removeJob(div)
{
document.getElementById("employmentHistory").removeChild(div.parentNode);
i--;
};
button
{
height: 20px;
width: 20px;
background: none;
margin-left: 10px;
margin-top: 30px;
margin-bottom: 25px;
}
input[type="button"]
{
height: 20px;
width: 20px;
background: none;
border: 1px solid #ccc;
outline: none;
margin-left: 20px;
}
input[type="button"]:focus
{
outline: none;
}
input.three-lines
{
margin-left: 18px;
background: none;
border: none;
border-bottom: 1px solid #b3c1cc;
width: 150px;
margin-bottom: 30px;
}
<div id="page2-content">
<div class="input-group" id="previousTeachingExperience">
<label id="teachingExpierience">Teaching Experience *</label>
<div id="employmentHistory">
<input type="text" class="three-lines" name="schoolBoard_1" placeholder="School Board" onblur="this.placeholder='Email'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="position_1" placeholder="Position" onblur="this.placeholder='Position'" onfocus="this.placeholder=''" />
<input type="text" class="three-lines" name="years_1" />
<input type="button" name="myButton" onclick="addJob()" value="+" />
</div>
Hoping this will help you :)

Related

How to calculate percentage with simple JavaScript code

I have already created a form in html and linked it with my style sheet and also JavaScript page.
My problem is displaying the result on the form.
Can someone please take a look at the JavaScript code and tell me what I am doing wrong?
See the snippet for more details
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.onsubmit = e=>e.preventDefault() // disable form submit
;
myForm.oninput = percentageCalculator;
function percentageCalculator(amount, percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If you want to make result instantly on click of the input boxes then, make addEventListerner to input elements then get the value inside percentageCalculator and make calculation accordingly..
I have not modified anything from your HTML and only modified the JS part..
const myForm = document.getElementById('my-form');
const percent = document.querySelector('[name="percent"]');
const amount = document.querySelector('.amount');
const result = document.querySelector('[name="result"]');
function percentageCalculator() {
result.value = ((percent.value * amount.value) / 100).toFixed(2)
}
myForm.addEventListener('submit', e=>e.preventDefault())
myForm.addEventListener('input', percentageCalculator)
// myForm.result.value = percentageCalculator()
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br><br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
If it is possible for you to modify HTML template then you can add name attribute to the amount input as well then you can get the element with myForm.inputName..
Alternative solution: https://codepen.io/Maniraj_Murugan/pen/KKpdgXo
Use oninput as I did below. Also give the amount input field a name. it's missing in the OP.
// Percentage Calculator
const myForm = document.getElementById('my-form');
myForm.oninput = () => {
myForm.result.value = percentageCalculator(myForm.amount.value, myForm.percent.value);
}
function percentageCalculator(amount, percent) {
return ((percent * amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" name="percent" step=any min=0> % of </append>
<label><input type="number" name="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output name="result" value='0'></output>
<br>
<button type="reset">Reset Calculator!</button>
</fieldset>
</form>
Pass the parameters into the function as a local scope and return the result back.
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
myForm.result.value = percentageCalculator()
// Percentage Calculator
const calculatedResult = document.getElementById('result');
function mySubmitFunction(e) {
e.preventDefault();
const percent = document.getElementById('percent').value;
const amount = document.getElementById('amount').value;
calculatedResult.value = percentageCalculator(amount,percent);
return false;
}
function percentageCalculator(amount,percent) {
return ((percent *amount) / 100).toFixed(2)
}
fieldset { margin-top: 1em;
}
label {
display: inline-block; width: 8em; text-align: left;
}
input {
font-size: .8em; text-align: left; display: inline-block; width: 8em;
}
output::before {
content: '';
}
output {
font-weight: bold; width: 16em; border-bottom: 1px solid lightgrey; display: block; margin: .8em; float: right; text-align: right;
}
<h2>Percentage Calculator</h2>
<form action="" onsubmit="return mySubmitFunction(event)" id="my-form">
<fieldset>
<legend>Calculate Percentage :</legend>
<append>What is <input type="number" id="percent" name="percent" step=any min=0> % of </append>
<label><input type="number" id="amount" class="amount" step=any min=0></label>
</fieldset>
<fieldset><br>
<legend>Result :</legend>
<output id="result" name="result" value='0'></output>
<br><br>
<button type="submit">Calculate!</button>
</fieldset>
</form>
Your mistake:
Submit button instead of reset
Prevent default once it's submitted
reference element using ID

Javascript - I can not see the result of the sum of values

I have a design problem in the script that gives me the values ​​of the right column (ignoring the values ​​on the left), and the result of the sume I can not see in the green box when I click on "View Result"
// Old script
/*window.sumInputs = function() {
var inputs = document.getElementsByTagName('input'),
result = document.getElementById('total'),
sumar = 0;
for(var i=0; i<inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sumar += parseInt(ip.value) || 0;
}
}
result.value = sumar;
}*/
// ========================
// New script
$(document).ready(function() {
var valores = $('#derecha').children();
var suma = 0;
$.each(valores, function() {
valor = $(this).val() || 0;
suma += parseInt(valor);
});
//console.log(suma);
valores = document.getElementById('total');
});
body p {
margin: 0 20px
}
/*#izquierda {display:none}*/
#izquierda,
#derecha {
display: inline-block;
vertical-align: top;
width: 140px;
margin: 20px 20px 20px 20px;
padding: 10px;
border: 1px solid #000
}
#izquierda span,
#derecha span,
body span {
font-weight: bold
}
#izquierda p,
#derecha p {
margin: 5px auto 15px;
text-align: center
}
input {
width: 80px;
display: block;
margin: 5px auto;
padding: 2px 0;
background: #f2f2f2;
border: none;
border: 1px solid #000;
text-align: center
}
#cont-resultado {
text-align: center;
width: 120px;
padding-left: 40px
}
#cont-resultado input {
display: inline-block;
margin: 0 auto 10px;
background: red;
color: #fff;
border: none;
padding: 10px 0
}
#cont-resultado a {
display: inline-block;
text-decoration: none;
color: #fff;
background: green;
padding: 10px 12px
}
#total {
display: block
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="izquierda">
<p><span>DIV LEFT</span><br>display="none"</p>
<input name="qty1" value="240">
<input name="qty2" value="862">
<input name="qty3" value="911">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="derecha">
<p><span>DIV RIGHT</span><br>display="block"</p>
<input name="qty1" value="2">
<input name="qty2" value="2">
<input name="qty3" value="2">
<input name="qty4" value="">
<input name="qty5" value="">
<input name="qty6" value="">
<input name="qty7" value="">
<input name="qty8" value="">
</div>
<!-- ================ -->
<div id="cont-resultado">
<input name="total" id="total">
See total
</div>
<br>
<p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
What am I doing wrong...?
Thanks in advance!
$(document).ready(function(){
var valores = $('#derecha').children();
var suma = 0;
$.each(valores,function(){
valor = $(this).val() || 0;
suma += parseInt( valor );
});
//console.log(suma);
valores = document.getElementById('total');
});
You're not doing anything with suma, further, use a selector for the children .children('input').
$(document).ready(function() {
function sumInputs(e) {
e.preventDefault();
var valores = $('#derecha').children('input');
var suma = 0;
$.each(valores, function() {
valor = $(this).val();
suma += Number(valor);
});
valores = document.getElementById('total');
$(valores).val(suma);
}
$('#sumup').on('click', sumInputs);
});
body p { margin: 0 20px}/*#izquierda {display:none}*/#izquierda,#derecha { display: inline-block; vertical-align: top; width: 140px; margin: 20px 20px 20px 20px; padding: 10px; border: 1px solid #000}#izquierda span,#derecha span,body span { font-weight: bold}#izquierda p,#derecha p { margin: 5px auto 15px; text-align: center}input { width: 80px; display: block; margin: 5px auto; padding: 2px 0; background: #f2f2f2; border: none; border: 1px solid #000; text-align: center}#cont-resultado { text-align: center; width: 120px; padding-left: 40px}#cont-resultado input { display: inline-block; margin: 0 auto 10px; background: red; color: #fff; border: none; padding: 10px 0}#cont-resultado a { display: inline-block; text-decoration: none; color: #fff; background: green; padding: 10px 12px}#total { display: block}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="izquierda"> <p><span>DIV LEFT</span><br>display="none"</p> <input name="qty1" value="240"> <input name="qty2" value="862"> <input name="qty3" value="911"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="derecha"> <p><span>DIV RIGHT</span><br>display="block"</p> <input name="qty1" value="2"> <input name="qty2" value="2"> <input name="qty3" value="2"> <input name="qty4" value=""> <input name="qty5" value=""> <input name="qty6" value=""> <input name="qty7" value=""> <input name="qty8" value=""></div><!-- ================ --><div id="cont-resultado"> <input name="total" id="total"> <a id='sumup' href="#">See total</a></div><br><p>What I am looking for is that only the RIGHT column is sumed, ignoring the values in the left column. <br><br><span>The result of example (6) must be seen in the red box...</span></p>
You need to set the value of valores (the new one) to suma:
valores.val(suma);

Transfer input from prompt() into a text field

I have a HTML page in which when the start button is being pressed, a prompt box will appear to prompt the user to enter his/her name. When user enters his/her name and confirms the input, it would appear on the black box (as shown in the code) with white text color. I am not sure of how to "transfer" the value from prompt() to text field. I know the value of the input fields are empty by default.
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
person = document.getElementById(input).value;
}
}
#input{
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit{
width: 30px;
margin: 5px;
display: block;
font-weight:bold;
text-align:center;
font-size:10px;
line-height:15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input"/>
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1"/>
Expected output would be for the user to enter his/her name in the prompt and upon confirmation, his/her name will appear in the text field in black with white text colors.
You just need to swap it.
person = document.getElementById(input).value;
The above is wrong. It should be:
document.getElementById("input").value = person;
And you need to update the "input" too. It's not a constant.
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById("input").value = person;
}
}
#input {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit {
width: 30px;
margin: 5px;
display: block;
font-weight: bold;
text-align: center;
font-size: 10px;
line-height: 15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input" />
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1" />
function myFunction() {
var person = prompt("Please enter your name");
if (person != null) {
document.getElementById('input').value = person;
}
}
#input{
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #191818;
color: white;
}
#input1 {
width: 15%;
padding: 50px 50px;
margin: 8px 0;
background-color: #7C7878;
color: white;
}
.btnEdit{
width: 30px;
margin: 5px;
display: block;
font-weight:bold;
text-align:center;
font-size:10px;
line-height:15px;
}
<h2>Part 3</h2>
<button onclick="return myFunction()" id="strt" value="Start">Start</button>
<button onclick="return reset()" id="clr" value="Clear">Clear</button> <br />
<br>
<input type="text" id="input" style="text-align:center;" name="input"/>
<button id="swap" value="Swap" class="btnEdit">--></button>
<button id="swap1" value="Swap1" class="btnEdit"><--</button>
<input type="text" id="input1" value="" style="text-align:center;" name="input1"/>

Disable input button when field.value is empty

I've seen this answered in jquery, but I'd like to know how I can do it in javascript. So far I came up with the following, but I understand it is not capturing the nameF.value properly.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
if (nameF.value == "") {
formButton.classList.add("notclickable");
}
}
go();
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button">
https://stackoverflow.com/questions/ask#
How can I do it without jQuery, just using vanilla?
Thank you!
All you need is an event handler assigned to nameF, and to .toggle() the class instead of add().
The .toggle() receives an optional second argument where you tell it if it should add or remove the class, so you'll pass the string comparison there.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.classList.toggle("notclickable", nameF.value == "");
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
opacity: 1;
}
#form-button.notclickable {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#
Also, be aware that you don't need a class to disable the button. You can use the disabled property with the :disabled selector. This disables its functionality too instead of just fading it.
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function go() {
formButton.disabled = nameF.value == "";
}
go();
nameF.addEventListener("input", go);
#form-button {
cursor: pointer;
outline: none;
border: none;
font-family: $body-font;
font-size: 14px;
padding: 16px;
color: #fff;
font-weight: 800;
background-color: #000;
position: relative;
border-radius: 2px;
}
#form-button:disabled {
opacity: .1;
pointer-events: none;
}
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button"> https://stackoverflow.com/questions/ask#
Try something like that!
var nameF = document.getElementById("name-field");
var formButton = document.getElementById("form-button");
function onChangeContent(e) {
formButton.disabled = e.target.value !== '' ? false : true;
}
nameF.addEventListener('keyup', onChangeContent);
<input type="text" name="name" class="form-style form-field" id="name-field" placeholder="Your name">
<input type="submit" value="Send" id="form-button" disabled>

Validate if radio button was checked?

I have the scripts below to validate text field..
< script src = "https://img.en25.com/i/livevalidation_standalone.compressed.js"
type = "text/javascript" >
< script type = "text/javascript" >
var dom1 = document.querySelector('#form3471 #field1');
var field1 = new LiveValidation(dom1, {
validMessage: "",
onlyOnBlur: false,
wait: 300
});
field1.add(Validate.Presence, {
failureMessage: "This field is required"
});
< /script>
<form method="post" name="" action="https://s1788.t.eloqua.com/e/f2" onsubmit="setTimeout(function(){if(document.querySelector){var s=document.querySelector('form#form3471 input[type=submit]');if(s){s.disabled=true;}}},100);return true;" id="form3471"
class="elq-form">
<label for="field1" style="display: block; line-height: 150%; padding: 1px 0pt 3px; float: left; width: 31%; margin: 0pt 15px 0pt 0pt; word-wrap: break-word">Name:*</label>
<input id="field1" name="C_FirstName" type="text" value="" style="width: 46%">
I added some radio buttons & would like to validate the radio buttons as well, how do I modify them to work for radio button?
<label for="field0" style="display: block; line-height: 150%; padding: 1px 0pt 3px; white-space: nowrap">Country*</label>
<label style="display: block; float: left; padding-right: 10px; padding-left: 22px; text-indent: -22px">
<input name="radioButtons" type="radio" value="country1" style="vertical-align: middle; margin-right: 7px">
<span style="vertical-align: middle">Country1</span>
</label>
<label style="display: block; float: left; padding-right: 10px; padding-left: 22px; text-indent: -22px">
<input name="radioButtons" type="radio" value="country2" style="vertical-align: middle; margin-right: 7px">
<span style="vertical-align: middle">Country2</span>
</label>
Do a function for your radiobutton. Right now you don't have a function for it.
Like this:
function myFunction() {
var answer = document.getElementById("radioBtn").checked;
document.getElementById("value").innerHTML = answer;
}
http://codepen.io/anon/pen/oBPpZz
Please try this
if ($('input[name=radioButtons]:checked').val() == 'country1' ) {
//validation
}

Categories