What I basically am trying to accomplish is a form, where one can add a whole html line dynamically using javascript using one button, or remove an existing line using another.
I got the add function to work, yet I cannot seem to figure out the remove function.
Here is my code:
window.onload = function(){
var addHw = document.getElementById("addhw");
var removeHw = document.getElementById("removehw");
// Here is my add function
addHw.addEventListener('click', function () {
var homeworkGrade = document.createElement('input');
homeworkGrade.className = 'grade';
homeworkGrade.type = 'text';
homeworkGrade.size = 3;
var overallGrade = document.createElement('homework');
overallGrade.className = 'homework';
overallGrade.type = 'text';
overallGrade.size = 3;
var form = document.getElementById("assignments");
var r = "HW <input class=\"grade\" type = \"text \"size=\"3 \">/<input class=\"homework \" type = \"text \" size= \"3 \"><br />";
form.insertAdjacentHTML('beforeend',r);
});
// Here is my attempt at the remove function:
removeHw.addEventListener('click', function () {
var form = document.getElementById("assignments").lastChild;
var hw = document.getElementById("homework");
var grade = document.getElementById("grade");
});
}
<form id="myForm">
<div id="assignments">
<!-- add HWs here -->
HW <input class="grade" type="text" size="3">/<input class="homework" type="text" size="3"><br />
HW <input class="grade" type = "text" size="3 ">/<input class="homework " type = "text " size= "3 "><br />
HW <input class="grade" type = "text "size="3 ">/<input class="homework " type = "text " size= "3 "><br />
</div>
<div>
<!-- add curve here -->
<input type="checkbox" name="curve" />Curve + 5?
</div>
<div id="resultsarea ">
<p>
<!--add buttons-->
<button type="button" id="compute">Compute!</button>
<button type="button" id="addhw">Add HW</button>
<button type="button" id="removehw">Remove HW</button>
<button type="button" id="clear">Clear</button>
</p>
<!-- add the results here -->
<div id="result"></div>
</div>
</form>
I tried the removeChild and tried to remove the last child of "assignments", with no luck.
If someone would like to comment on my code and if it's efficient or provide me some comments that would benefit my progress, I'll be the most thankful.
By far the easiest way to do it is to update your code so that your "HW" are wrapped (e.g. in a span), and give all of these spans a class (e.g. "hw").
If you want them to be in different lines anyway, you may as well use a p or a div and remove the <br />.
window.addEventListener('load', function(){
var addHw = document.getElementById('addhw');
var removeHw = document.getElementById('removehw');
var hwHTML = '<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>';
var form = document.getElementById("assignments");
// Add hw.
addHw.addEventListener('click', function () {
// A lot of core were useless here as you only
// use the string at the end (and it is sufficient).
form.insertAdjacentHTML('beforeend', hwHTML);
});
// Remove hw.
removeHw.addEventListener('click', function () {
form.removeChild(form.querySelector(".hw:last-child"));
});
});
<form id="myForm">
<div id="assignments">
<!-- add HWs here -->
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
<div class="hw">HW <input class="grade" type="text" size="3" />/<input class="homework" type="text" size="3" /></div>
</div>
<div>
<!-- add curve here -->
<input type="checkbox" name="curve" />Curve + 5?
</div>
<div id="resultsarea ">
<p>
<!--add buttons-->
<button type="button" id="compute">Compute!</button>
<button type="button" id="addhw">Add HW</button>
<button type="button" id="removehw">Remove HW</button>
<button type="button" id="clear">Clear</button>
</p>
<!-- add the results here -->
<div id="result"></div>
</div>
</form>
It would be great to place every HW into its container. Because removal of the whole container is much easier.
Javascript:
(function(){
var addHw = document.getElementById("addhw");
var removeHw = document.getElementById("removehw");
// Here is my add function
addHw.addEventListener('click', function () {
var form = document.getElementById("assignments");
var r = "<div>HW <input class=\"grade\" type = \"text \"size=\"3 \">/<input class=\"homework \" type = \"text \" size= \"3 \"></div>";
form.insertAdjacentHTML('beforeend',r);
});
// Here is my attempt at the remove function:
removeHw.addEventListener('click', function () {
var form = document.getElementById("assignments");
var lastHW = form.lastChild;
if(lastHW) {
form.removeChild(lastHW);
}
});
})();
Html:
...
<div id="assignments">
<!-- add HWs here -->
<div>HW <input class="grade" type="text" size="3">/<input class="homework" type="text" size="3"></div>
<div>HW <input class="grade" type = "text" size="3 ">/<input class="homework " type = "text " size= "3 "></div>
<div>HW <input class="grade" type = "text "size="3 ">/<input class="homework " type = "text " size= "3 "></div>
</div>
...
Example: https://jsfiddle.net/61ytuoyb/
Can you try wrapping the individual assignments in an assignment and add a unique identifier to each assignment ?
<div id="assignments">
<div id="assignment_1">HW etc ...</div>
<div id="assignment_2">HW etc ...</div>
<div id="assignment_3">HW etc ...</div>
</div>
Use like a global counter variable to create the unique identifier for each assignment.
Then use the javascript
var idToDelete;
addHw.addEventListener('click', function () {
idToDelete = this.id; //not sure this is how to obtain the id in pure js.
});
removeHw.addEventListener('click', function () {
var parent = document.getElementById("assignments");
var child = document.getElementById("assignment_" + idToDelete);
parent.removeChild(child);
});
This off the top of my head. Untested code.
Related
I need the following output as shown in the gif below.
I created three inputs which I put in the box below. How can I have such output?
Please help with an example
NOTE:Suppose we have 50 inputs and the class is the same
I can't use it after Get ID
MY HTML code
<span class="pricing-heading">Your sale price:</span><div class="pricing-field"><input class="pricing-set-price" type="number" value="24.00"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span><div class="pricing-field"><input class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span><div class="pricing-field"><input class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
JS code :
$(".pricing-set-price").change(function(){
var item_rrp = $(this).val();
var item_base = $(this).parent().parent().parent().find('.pricing-base-price').val();
var profit = item_rrp - item_base;
var profit_format = profit.toFixed(2);
$(this).parent().parent().parent().find('.pricing-profit').val(profit_format);
});
You may try like
$(".pricing-set-price").change(function(){
let currentValue = $(this).val();
var previousValue = this.defaultValue;
if(previousValue < currentValue){
this.defaultValue = currentValue;
console.log('Increment');
}else{
console.log('Decrement');
}
});
You can call the function that changes the value of Profit (input) on the onchange , oninput, or onClick events of the SalePrice(input)
function increment() { document.getElementById('salePrice').stepUp();
calculateProfit()
}
function decrement() {
document.getElementById('salePrice').stepDown();
calculateProfit()
}
function calculateProfit(){
let sp = document.getElementById("salePrice").value;
document.getElementById("profit").value = sp - 10;
}
<input id="salePrice" type=number value=10 min=10 max=110 />
<button onclick="increment()">+</button>
<button onclick="decrement()">-</button>
<br/>
Base Price :: <input type="text" id="basePrice" value=10
disabled >
<br/>
Profit :: <input type="text" id="profit" value=0 />
For more info about:
stepUp()
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/stepUp
stepDown()
https://www.w3schools.com/Jsref/met_week_stepdown.asp
Hi i think this might help. use id for your input fields.
function calculateProfit(val){
var baseCost = document.getElementById("baseCost").value;
document.getElementById("Profit").value = (val - baseCost).toFixed(2);
}
<div class="prt-pricing-heading">
<span class="pricing-heading">Your sale price:</span>
<div class="pricing-field"><input id="SalePrice" class="pricing-set-price" type="number" value="24.00" onchange="calculateProfit(this.value);" oninput="calculateProfit(this.value)"></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Product base Cost:</span>
<div class="pricing-field"><input id="baseCost" class="pricing-base-price" type="number" value="10.00" disabled></div>
</div>
<div class="prt-pricing-detial">
<span class="pricing-heading">Your profit:</span>
<div class="pricing-field"><input id="Profit" class="pricing-profit" type="number" value="14.00" disabled></div>
</div>
For More info regarding:
oninput() https://www.w3schools.com/tags/att_oninput.asp
onchange() https://www.w3schools.com/tags/ev_onchange.asp
I am creating a multi-page form (by which I mean on certain button clicks, specific elements change between hidden and visible) following this page's setup. I have 2 pages: 1. add animal and 2. add another animal. I would like to be able to repeat page 2 as many times as the user clicks the button add another animal before they click submit, and store all the inputted animal names to be sent to a python function (so every time a user types in a name on the add another animal page, the previous animal's name isn't overwritten.
My HTML, CSS, and JS are below.
<div class="section-25">
<div class="container-5 w-container">
<div class="text-block-6">Select the level of algorithm you're looking to make</div>
<div class="w-form">
<form id="wf-form-Email-Form" name="wf-form-Email-Form" data-name="Email Form" method="post" action="/add_animal">
<!-- PAGE 1 -->
<div id="page1" class="page">
<!-- 1ST ANIMAL NAME -->
<label for="Enter-species" class="custom-question enter-species" id="one_name">What animal are you interested in?</label>
<input type="text" class="text-field w-input" maxlength="256" name="species" placeholder="Enter name of animal" id="Enter-species" required="">
<p><input type="button" id="C1" value="Add another animal" onClick="showLayer('page2')"></p>
</div>
<!-- PAGE 2 -->
<div id="page2" class="page">
<!-- NEXT ANIMAL NAME -->
<label for="Enter-species" class="custom-question enter-species" id="one_name">What other animal are you interested in?</label>
<input type="text" class="text-field w-input" maxlength="256" name="another_species" placeholder="Enter name of animal" id="Enter-species">
<p><input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="button" id="C2" value="Add another animal" onClick="showLayer('page2')">
<input type="button" id="S1" value="Submit" action="/add_animal" </p>
</div>
</form>
</div>
</div>
</div>
CSS:
<!-- CSS -->
<style>
.page {
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
</style>
JS:
<!-- JAVASCRIPT -->
<script language="JavaScript">
var currentLayer = 'page1';
function showLayer(lyr) {
hideLayer(currentLayer);
document.getElementById(lyr)
.style.visibility = 'visible';
currentLayer = lyr;
}
function hideLayer(lyr) {
document.getElementById(lyr).
style.visibility = 'hidden';
}
function showValues(form) {
var values = '';
var len = form.length - 1;
//Leave off Submit Button
for (i = 0; i < len; i++) {
if (form[i].id.indexOf("C") != -1 ||
form[i].id.indexOf("B") != -1)
//Skip Continue and Back Buttons
continue;
values += form[i].id;
values += ': ';
values += form[i].value;
values += '\n';
}
alert(values);
}
</script>
i think you mean something like this:
let currentLayer = 0;
const animalList = [];
const form = document.getElementById("wf-form-Email-Form");
const [field, backButton, addButton, submitButton] = form.elements;
function showLayer(lyr) {
switch(lyr){
case 1:
currentLayer++;
if (currentLayer-1 == animalList.length){
animalList.push(field.value)
form.reset();
backButton.style.display = 'unset';
}else{
if (currentLayer == animalList.length){
addButton.value = 'Add another animal';
field.value = "";
}else{
addButton.value = 'Next';
field.value = animalList[currentLayer];
}
}
break;
case -1:
currentLayer--;
if(!currentLayer) backButton.disabled = true;
if (currentLayer < animalList.length +1){
field.value = animalList[currentLayer];
addButton.value = 'Next';}
break;
}
}
submitButton.onClick = function(e){
// serialize animalList and send using AJAX or add a hidden type input and set animalList as it's value
}
.page {
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
#backButton{
display:none;
}
<div class="section-25">
<div class="container-5 w-container">
<div class="text-block-6">Select the level of algorithm you're looking to make</div>
<div class="w-form">
<form id="wf-form-Email-Form" name="wf-form-Email-Form" data-name="Email Form" method="post" action="/add_animal">
<label for="Enter-species" class="custom-question enter-species" id="one_name">What other animal are you interested in?</label>
<input type="text" class="text-field w-input" maxlength="256" name="another_species" placeholder="Enter name of animal" id="Enter-species">
<p>
<input type="button" id="backButton" value="Go Back" onClick="showLayer(-1)">
<input type="button" id="addButton" value="Add another animal" onClick="showLayer(+1)">
<input type="button" id="submit" value="Submit">
</p>
</form>
</div>
</div>
</div>
I would like for every different item inputted to be outputted in a new box.
<!DOCTYPE html>
<html>
<body>
Form to get the input
<form id="form1">
<input name="item" type="text" size="20">
</form>
Box that should be duplicated to hold the new input.
<div class="box">
<p class="output"></p>
<div>
<button onclick="outputItem()">Add</button>
javascript:
<script>
function outputItem() {
var x = document.getElementById("form1");
item = x.elements.namedItem("item").value;
document.getElementById("output").innerHTML=item;
</script>
</body>
</html>
I am not sure if this is even close to what you want, but give this a try:
function outputItem() {
var els = document.querySelectorAll("#form1 input");
var box = document.querySelector('.box');
box.innerHTML = '';
els.forEach(
function(el) {
var newEl = document.createElement('div');
newEl.innerHTML = el.value;
box.appendChild(newEl);
}
);
}
<form id="form1">
<input name="item" type="text" size="20" value="item"><br/>
<input name="eggs" type="text" size="20" value="eggs"><br/>
<input name="milk" type="text" size="20" value="milk"><br/>
<input name="grains" type="text" size="20" value="grains"><br/>
<input name="legumes" type="text" size="20" value="legumes"><br/>
</form>
<button onclick="outputItem()">Add</button>
<hr/>
<div class="box"></div>
This creates a new <div> for every input and copies the .value from the <input> into the new <div>. Then it adds the <div> into the output area.
As the title would suggest I keep getting that error when trying to test out a basic script which would "read" form inputs and make them variables to use later on.
HTML:
<script type="text/javascript" language="javascript"
src="./js/lisearch.js"></script>
<form name="search" action="" method="post">
<h2>Include:</h2>
<div id="formtitle" class="formdiv">
<p> Current Job Title:</p><input id="jtitle" type="text" name="jobtitle" placeholder="Demand planner, Supply planner">
</div>
<div id="formcompany" class="formdiv">
<p> Current Company:</p><input id="cmpy" type="text" name="company" placeholder="GSK OR Danone">
</div>
<div id="formkeywords" class="formdiv">
<p> Keywords:</p><input id="kwrd" type="text" name="keywords" placeholder="(SAP OR JDE) AND FMCG">
</div>
<div id="formfirst" class="formdiv">
<p> First Name:</p><input id="fname" type="text" name="first">
</div>
<div id="formlast" class="formdiv">
<p> Last Name:</p><input id="lname" type="text" name="last">
</div>
<hr>
<h2> Exclude:</h2>
<div id="formnottitle" class="formdiv">
<p> Current Job Title:</p><input id="njtitle" type="text" name="notjobtitle" placeholder="Manager OR Consultant">
</div>
<div id="formnotcompany" class="formdiv">
<p> Current Company:</p><input id="ncmpy" type="text" name="notcompany" placeholder="Coke OR Pepsi">
</div>
<div id="formnotkeywords" class="formdiv">
<p> Keywords:</p><input id="nkwrd" type="text" name="notkeywords" placeholder="Recruiter OR Recruitment">
</div>
<div id="submit" class="formdiv">
<input type="button" value="Create Search" onclick="onclick()">
</div>
<div id="output" class="formdiv">
<input type="text" name="output">
</div>
</form>
JS:
var company;
var jobtitle;
var keywords;
var fname;
var lname;
var notcompany;
var notjobtitle;
var notkeywords;
function onclick() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
test();
}
function test() {
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
As you can probably tell I am really new to all this but can't seem to figure this out, any help appreciated.
Thanks,
This kind of message you get when doing recursive calls and get stuck somewhere in a cycle. in your case rename onclick() function to something else, that's it!
Here I made a plunker
function toto() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
test();
}
function test() {
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
and
<input type="button" value="Create Search" onclick="toto()">
put function test at the top of your js code so that onclick() knows what it is when the event handler is assigned.
Edit: Additional feedback:
The test function isn't even needed. Just insert the alert code into the onclick function.
edit: Moving the script tags shouldn't actually have any effect. I am not sure what is going wrong here.
Edit:solved it
<form name="search" action="" method="post">
<h2>Include:</h2>
<div id="formtitle" class="formdiv">
<p> Current Job Title:</p><input id="jtitle" type="text" name="jobtitle" placeholder="Demand planner, Supply planner">
</div>
<div id="formcompany" class="formdiv">
<p> Current Company:</p><input id="cmpy" type="text" name="company" placeholder="GSK OR Danone">
</div>
<div id="formkeywords" class="formdiv">
<p> Keywords:</p><input id="kwrd" type="text" name="keywords" placeholder="(SAP OR JDE) AND FMCG">
</div>
<div id="formfirst" class="formdiv">
<p> First Name:</p><input id="fname" type="text" name="first">
</div>
<div id="formlast" class="formdiv">
<p> Last Name:</p><input id="lname" type="text" name="last">
</div>
<hr>
<h2> Exclude:</h2>
<div id="formnottitle" class="formdiv">
<p> Current Job Title:</p><input id="njtitle" type="text" name="notjobtitle" placeholder="Manager OR Consultant">
</div>
<div id="formnotcompany" class="formdiv">
<p> Current Company:</p><input id="ncmpy" type="text" name="notcompany" placeholder="Coke OR Pepsi">
</div>
<div id="formnotkeywords" class="formdiv">
<p> Keywords:</p><input id="nkwrd" type="text" name="notkeywords" placeholder="Recruiter OR Recruitment">
</div>
<div id="submit" class="formdiv">
<input type="button" id="onclick" value="Create Search"/>
</div>
<div id="output" class="formdiv">
<input type="text" name="output"/>
</div>
</form>
<script type="text/javascript">
var company;
var jobtitle;
var keywords;
var fname;
var lname;
var notcompany;
var notjobtitle;
var notkeywords;
document.getElementById("onclick").onclick=function() {
company = document.getElementById('cmpy').value;
jobtitle = document.getElementById('jtitle').value;
keywords = document.getElementById('kwrd').value;
fname = document.getElementById('fname').value;
lname = document.getElementById('lname').value;
notcompany = document.getElementById('ncmpy').value;
notjobtitle = document.getElementById('njtitle').value;
notkeywords = document.getElementById('nkwrd').value;
alert(company + jobtitle + keywords + fname + lname + notcompany + notjobtitle + notkeywords);
}
</script>
I'm trying to make a page where a user can enter a url and some text (like an image caption) and when they click the button the url and text will be added to an empty array (which can be accessed by a different script and published on the page). My question is how do I write a function and/or an array for this? What from my code below is wrong and what can I do to fix it? Thanks!
<script>
var annotatedImageArray = new Array();
var imageInput = document.getElementById("imageInput");
var image = imageInput.value;
var captionInput = document.getElementById("captionInput");
var caption1 = captionInput.value;
annotatedImageArray.push({url:image, caption:caption1});
</script>
<body>
<input type="text" size="30" id="imageInput" placeholder="Enter URL">
<input type="text" size="30" id="captionInput" placeholder="Enter Caption">
<input type="button" value="Add Image" onclick=""/>
</body>
you can try something like this:
(you can play around with it over here:http://jsfiddle.net/marcelow/NdAkz/)
<script>
(function(window) {
window['annotatedImageArray'] = [];
window['addImage'] = function() {
var imageInput = document.getElementById("imageInput");
var image = imageInput.value;
var captionInput = document.getElementById("captionInput");
var caption1 = captionInput.value;
annotatedImageArray.push({url:image, caption:caption1});
}
})(window);
</script>
<body>
<input type="text" size="30" id="imageInput" placeholder="Enter URL">
<input type="text" size="30" id="captionInput" placeholder="Enter Caption">
<input type="button" value="Add Image" onclick="addImage();"/>
</body>