How do I make each new output appear in a new box? - javascript

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.

Related

Adding Number Result in NaN

<script>
function myFunction(val) {
const ele = document.querySelectorAll('input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
Why the result is NaN? But if I remove the value="Submit" in the last 5th line, then everything working fine. Why? and what should I do to solve this problem?
Your
const ele = document.querySelectorAll('input');
will iterate over all inputs, including the <input type="submit" name= "submit" id="submit" value="Submit"/>.
When you don't use value="Submit", that element doesn't have a real .value, so it defaults to the empty string:
console.log(submit.value);
console.log(submit.value.length);
<input type="submit" name="submit" id="submit">
In contrast, <input value="Submit"/> will have a .value of Submit, which can't be turned into a number.
Select only your inputs with input classes instead:
function myFunction() {
const ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name="submit" id="submit" value="Submit" /></p>
Also note that duplicate IDs are invalid HTML, and event handlers should be attached properly using Javascript instead of using inline handlers:
const inputs = document.querySelectorAll('input.input');
inputs.forEach((input) => {
input.addEventListener('keydown', () => {
const sum = [...inputs].reduce((a, input) => a + Number(input.value), 0);
document.getElementById('result').textContent = sum.toFixed(2);
});
});
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" class="input">
<input type="text" class="input">
<p id="result"></p>
<br>
<p><input type="submit" value="Submit"></p>
</form>
Because you are selecting all the input tag, you should be specific on selecting like querySelectorAll('input[type="text"]'). so it will select only text input tags. Try this one
<!DOCTYPE html>
<html>
<body>
<script>
function myFunction(val) {
const ele = document.querySelectorAll('input[type="text"]');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
}
</script>
<form action="test.php" method="POST" enctype="multipart/form-data">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<input type="text" id="array[]" class="input" oninput="myFunction(this.value)">
<p id="result"></p>
<br>
<p><input type="submit" name= "submit" id="submit" value="Submit"/></p>
</form>
</body>
</html>
Because document.querySelectorAll('input'); selecting all inputs including submit button as well which has value='submit' and value submit is not a number (NAN). When you remove value attribute from the submit button it returns nothing.

Why is my jQuery not adding display on second div I create?

When I try adding the first contact and submit it, it shows in the div id=contact.
The function hide/show is working then.
But as soon as I add a second contact it's not working anymore.
Seems, jQuery doesn't enter display...
function css(){
$('.contacts').css('background-color', 'lightblue');
}
function visibility() {
$("#vis").click(function(){
$(".description").toggle();
return false;
});
};
$( document ).ready(function() {
$("form").submit(function (event) {
var fname = $('#fname').val();
var lname = $('#lname').val();
var desc = $('#desc').val();
$('.contacts').append( "<div id='contact'>"+fname+"<br>"+lname+"<br><button id='vis'>Show/Hide</button><div class='description' style='display:;'>"+desc+"</div></div>");
// alert(fname);
event.preventDefault();
css();
visibility();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="get">
<fieldset>
<legend>Personal information:</legend>
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
</fieldset>
<fieldset>
<legend>Description:</legend>
<textarea id="desc" value="desc"> </textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<div class="contacts"> </div>
Any help would be appreciated, thanks.
As I wrote in comment - You can't have multiple elements with the same ID in html. You also don't have to add listeners for each button. You can add listener for body and selector as second parameter (see attached code).
function css(){
$('.contacts').css('background-color', 'lightblue');
}
$( document ).ready(function() {
//this way you don't need to add listener for each button
$('body').on('click', '.vis', function() {
$(this).closest('.contact').find('.description').toggle();
});
$("form").submit(function (event) {
var fname = $('#fname').val();
var lname = $('#lname').val();
var desc = $('#desc').val();
$('.contacts').append( "<div class='contact'>"+fname+"<br>"+lname+"<br><button class='vis'>Show/Hide</button><div class='description'>"+desc+"</div></div>");
event.preventDefault();
css();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#" method="get">
<fieldset>
<legend>Personal information:</legend>
First name: <input type="text" name="fname" id="fname"><br>
Last name: <input type="text" name="lname" id="lname"><br>
</fieldset>
<fieldset>
<legend>Description:</legend>
<textarea id="desc" value="desc"> </textarea><br>
<input type="submit" value="Submit">
</fieldset>
</form>
<div class="contacts"> </div>

How to create a unique id from the first two fields in the form?

I created a form with three fields first_name, Last_name, city and in the fourth field, I am having an Id column which is read-only. When the user fills the first three fields in the form, before submitting it should generate an id in the fourth column but here it should use the first two alphabets that are in the fields to generate an Id
For eg. First_name = Roid, Last_name = Steve, city = California then in the fourth field it should automatically generate this id = rostca (all the first two alphabets)
How to achieve this?
Here is a JavaScript version to answer to your issue.
(function () {
populate();
})();
function populate () {
var str = "";
Array.from(document.getElementsByClassName("inputs")).forEach(function (element) {
str += element.value.substr(0, 2).toLowerCase();
});
document.getElementById("output").value = str;
}
<div>
<input type="text" class="inputs" value="Roid" oninput="populate();" />
<input type="text" class="inputs" value="Steve" oninput="populate();" />
<input type="text" class="inputs" value="California" oninput="populate();" />
<input id="output" type="text" readonly disabled />
</div>
Here is a jQuery answer to your issue.
$(function () {
populate();
$(".inputs").on("input", function() {
populate();
});
});
function populate () {
var str = "";
$(".inputs").each(function () {
str += $(this).val().substr(0, 2).toLowerCase();
});
$("#output").val(str);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="inputs" value="Roid" />
<input type="text" class="inputs" value="Steve" />
<input type="text" class="inputs" value="California" />
<input id="output" type="text" readonly disabled />
</div>
Check below code,
function TextChanged(){
var first_name = document.getElementById("first_name").value;
var Last_name = document.getElementById("Last_name").value;
var city = document.getElementById("city").value;
document.getElementById("id").value = first_name.substring(0, 2) +Last_name.substring(0, 2) +city.substring(0, 2);
}
<input type="text" id="first_name" onblur="TextChanged()">
<input type="text" id="Last_name" onblur="TextChanged()">
<input type="text" id="city" onblur="TextChanged()">
<input type="text" id="id" readonly>
Check here jsbin demo, https://jsbin.com/qegazab/edit?html,js,console,output

How do I remove the whole last html line in div?

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.

Split urls/text by spaces into 2 boxes Javascript Only no libraries

Well so far i havent been able to get it to change the input box value.
What i want it to do?
I want it to take the text from the first box. And when you click the button splits it and appends them to the 2nd and 3rd box.
I don't want to use jquery or any libraries purely javascript.
Any questions ask away.
Not sure what im doing wrong here. Seems it should work. Any help? Thanks
Edited this is working for what i need.... not sure if its the best way but it does work
Code
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
var urls_1;
var split_text;
function addto_boxes(form) {
var split_text = document.getElementById("text_to_split").value;
var urls_1 = split_text.split(" ", 100000);
document.getElementById("input_box1").value = document.getElementById("input_box1").value + urls_1[0] + " ";
document.getElementById("input_box2").value = document.getElementById("input_box2").value + urls_1[1] + " ";
}
</SCRIPT>
</HEAD>
<BODY>
<input id="Split" type="button" value="Add to boxes" onclick="addto_boxes(this.form);"/><Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea><Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE=""rows="4" cols="75"></textarea><Br>
Put 2nd urls in this box: <Br>
<textarea NAME="inputbox2" id="input_box2" VALUE=""rows="4" cols="75"></textarea><Br>
<INPUT TYPE="reset">
</FORM>
</BODY>
</HTML>
This should work for you
HTML
<input id="Split" type="button" value="Add to boxes" />
<Br>
<textarea NAME="texttosplit" id="text_to_split" VALUE="" rows="4" cols="75"></textarea>
<Br>
<FORM NAME="myform" ACTION="" METHOD="GET">Put 1st urls in this box:
<textarea NAME="inputbox" id="input_box1" VALUE="" rows="4" cols="75"></textarea>
<Br>Put 2nd urls in this box:
<Br>
<textarea NAME="inputbox2" id="input_box2" VALUE="" rows="4" cols="75"></textarea>
<Br>
<INPUT id="reset" TYPE="reset">
</FORM>
Javascript
var aBox1 = [];
var aBox2 = [];
document.getElementById("Split").addEventListener("click", function () {
var urls_1 = document.getElementById("text_to_split").value.trim().split(" "),
url1 = urls_1[0] || "",
url2 = urls_1[1] || "";
if (url1.length) {
aBox1.push(url1);
}
if (url2.length) {
aBox2.push(url2);
}
document.getElementById("input_box1").value = aBox1.join(" ");
document.getElementById("input_box2").value = aBox2.join(" ");
}, false);
document.getElementById("reset").addEventListener("click", function () {
aBox1.length = 0;
aBox2.length = 0;
}, false);
On jsfiddle

Categories

Resources