Adding input fields to a HTML form - javascript

I want to dynamically add form input fields to a form using the javascript below by clicking on the add button:
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("Name", "a_level[ + i ][0]");
r.appendChild(y);
z.setAttribute("Name", "a_level[ + i ][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class = "dash-form" method = "POST" action = "/" >
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[+i][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[+i][1]" value = "" placeholder = "Course"/>
</div>
<div class = "dash-submit">
<input class = "dash-submit-button" type = "submit" value = "Submit"/>
</div>
</form>
<div class = "dash-add">
<button class = "dash-add-button" onclick = "addfieldFunction()">ADD</button>
</div>
The function returns an i instead of incrementing and returning an integer as shown below:
<div id = "form-div">
<input class = "dash-input" type = "text" name = "a_level[0][0]" value = "" placeholder = "University"/>
<input class = "dash-input" type = "text" name = "a_level[0][1]" value = "" placeholder = "Course"/>
</div>

Concatenate variable i using +(concatenation operator) operator
The concatenation operator (+) concatenates two string values together, returning another string that is the union of the two operand strings.
var i = 0;
function increment() {
i += 1;
}
function addfieldFunction() {
var r = document.createElement('div');
var y = document.createElement("INPUT");
var z = document.createElement("INPUT");
y.setAttribute("class", "dash-input");
y.setAttribute("type", "text");
y.setAttribute("placeholder", "University");
z.setAttribute("class", "dash-input");
z.setAttribute("type", "text");
z.setAttribute("placeholder", "Course");
increment();
y.setAttribute("name", "a_level[ " + i + " ][0]"); //Keep attribute in lower case
r.appendChild(y);
z.setAttribute("name", "a_level[ " + i + "][1]");
r.appendChild(z);
document.getElementById("form-div").appendChild(r);
}
<form class="dash-form" method="POST" action="/">
<div id="form-div">
<input class="dash-input" type="text" name="a_level[+i][0]" value="" placeholder="University" />
<input class="dash-input" type="text" name="a_level[+i][1]" value="" placeholder="Course" />
</div>
<div class="dash-submit">
<input class="dash-submit-button" type="submit" value="Submit" />
</div>
</form>
<div class="dash-add">
<button class="dash-add-button" onclick="addfieldFunction()">ADD</button>
</div>

You need to concatenate it like this:
y.setAttribute("name", "a_level[" + i +"][0]");
As Rayon pointed out: keep attributes in lower case although the HTML5 standard does not require lower case attribute names (see here). W3C recommends it though and XHTML validation would fail using uppercase letters.

Related

How to use HTML form input as JS variable

I am trying to make some element change color according to the number received from the form.
e.g. When a player types 2 in the form, there should be 2 colors from the 'color' array.
function intro() {
var num = document.getElementById('quant').value;
var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
var i;
for (i = 1; i <= 42; i++) {
document.getElementById('s' + i).style.backgroundColor = color[getRndInteger(0, num)];
}
}
<form id="tion" action="" method="get">
Player (between 2 and 6):
<input type="number" name="quant" min="2" max="6">
<input type="button" value="start" onclick="intro()">
</form>
Because you're not showing relevant parts of your code, I've simplified it. Your input was missing an id="quant" which I added.
function colorTheDiv() {
const color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
document.getElementById('colorMe').style.backgroundColor = color[parseInt(document.getElementById('quant').value)];
}
<label for="quant">Player (between 2 and 6)</label>
<input type="number" name="quant" id="quant" min="2" max="6" onchange="colorTheDiv()">
<hr />
<div id="colorMe">colorMe</div>
I've also replaced the button and execute the colorTheDiv function whenever the value of quant changes (if you prefer you can still keep the button instead).
Start by giving your field an ID of quant.
You are missing 42 elements too
I assume you ACTUALLY meant this
var color = ["#FCB711", "#F37021", "#CC004C", "#6460AA", "#0080D0", "#0DB14B"];
function getRndInteger(max) {
return Math.floor(Math.random() * max);
}
function intro() {
var container = document.getElementById("container");
container.innerHTML = "";
var num = document.getElementById('quant').value;
if (!num) {
alert("Give a value")
return;
}
for (var i = 1; i <= 42; i++) {
var col = color[getRndInteger(num)];
var span = document.createElement("span");
span.innerText = i;
span.id = "s" + i;
span.style.backgroundColor = col;
container.appendChild(span)
}
}
<form id="tion" action="" method="get">
Player (between 2 and 6):
<input type="number" id="quant" min="2" max="6">
<input type="button" value="start" onclick="intro()">
</form>
<div id="container"></div>
you need to give your field an ID of "quant" not just a name, otherwise getElementByID will return null

Generate user id using javascript and display it in textbox

So i need to display the user id that has been generated in javascript but i have problem to display it on textbox.
here's the javascript coding:
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
}
function SaveDetails(){
var CreateuserID = generateuserID();
document.getElementById('userID').value = CreateuserID;
var name = document.getElementById('userName').value;
var occupation = document.getElementById('userOccupation').value;
sessionStorage.setItem(name, occupation);
display();
var name = document.getElementById('userName').value = "";
var occupation = document.getElementById('userOccupation').value = "";
}
function display(){
var output = document.getElementById('output');
output.innerHTML = "";
for(var i=0;i<sessionStorage.length;i++)
{
var name = sessionStorage.key(i);
var occupation = sessionStorage.getItem(name);
output.innerHTML += name+"|"+occupation+"<br>";
}
}
function generateuserID()
{
var userIDnum = 1;
userIDnum++;
}
window.addEventListener('load', AddDetails, false);
This is the HTML code:
<!DOCTYPE HTML>
<html>
<head>
<link rel="stylesheet" href="Style.css">
<script src="script.js"></script>
</head>
<br>
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort">
<option value ="userID">userID</option>
<option value ="userID">userName</option>
<option value ="userID">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
</html>
Please help me i have been doing this for days and cant think of solution. I tried using ECMAScript and it wont work either. I'm still new and lack of knowledge.
Your generateuserID() method doesn't return anything. Even if your returned userIDnum everyone's user id will be 2. Do you realize that JavaScript just runs in the browser? None of the variables will exist between different users.
There are many mistakes in your sample. You don't need sessionStorage just for static content. Here is the working codepen [ https://codepen.io/vivekamin/pen/gQMRPx ] .I have created for you from your code. Please check it out. Here is the code. I have used createElement just for sake of working example. However, if you have many elements to append you can use createDocumentFragment which is more efficient. I am just adding the last data to HTML, output element in form of paragraph text
HTML:
<body>
<section id="input">
<form>
ID : <input type="number" readonly id="userID" value="">
Name : <input type="text" id="userName" >
Occupation : <input type="text" id="userOccupation">
<input type="button" id="button" value="Add">
</form>
</section>
<br>
<br>
Sort by: <select name="sort" id ="sortBy">
<option value ="userID">userID</option>
<option value ="name">userName</option>
<option value ="occupation">userOccupation</option>
</select>
<br>
<section id="output">
</section
</body>
JS Code:
let counter = 1;
let data = [];
function AddDetails(){
var button = document.getElementById('button');
button.addEventListener('click', SaveDetails, false);
let sortBy = document.getElementById('sortBy');
sortBy.addEventListener('change', SortAndDisplay, false);
document.getElementById('userID').value = counter;
}
function SortAndDisplay(){
console.log("Sorting", document.getElementById('sortBy').value);
let sortBy = document.getElementById('sortBy').value;
if(sortBy === "userID"){
data.sort(function (a, b) {
return a.id - b.id;
});
}
else{
sortByNameOrOccupation(sortBy);
}
console.log(data);
displayAfterSort();
}
function SaveDetails(){
let name = document.getElementById('userName');
let occupation = document.getElementById('userOccupation');
data.push({id: counter, name: name.value, occupation: occupation.value });
console.log(data);
counter++;
document.getElementById('userID').value = counter;
name.value='';
occupation.value ='';
let outputSection = document.getElementById('output');
let outputData = data[data.length - 1];
let newP = document.createElement('p');
newP.textContent = outputData['id'] + " " + outputData['name'] + " "+outputData['occupation'];
outputSection.appendChild(newP);
}
function sortByNameOrOccupation(attribute){
data.sort(function(a, b) {
var nameA = a[attribute].toUpperCase(); // ignore upper and lowercase
var nameB = b[attribute].toUpperCase(); // ignore upper and lowercase
if (nameA < nameB) {
return -1;
}
if (nameA > nameB) {
return 1;
}
// names must be equal
return 0;
});
}
function displayAfterSort(){
let outputSection = document.getElementById('output');
outputSection.innerHTML = '';
let fragment = document.createDocumentFragment();
data.forEach(function(d) {
let p = document.createElement('p');
p.textContent = d['id'] + " " + d['name'] + " "+d['occupation'];
fragment.appendChild(p);
});
outputSection.appendChild(fragment);
}
window.addEventListener('load', AddDetails, false);
To set the value of the textbox. Do:
$('#//ID of the textbox').val(CreateuserID)
This is assuming that 'CreateuserID' is a string or int
EDIT: Your CreateuserID function will need to return a value.

how to create an object with user input javascript

window.onload = Soldier;
function Soldier(allegiance,armor,weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
}
document.getElementById("soldier").innerHTML =
var soldier1 = new Soldier("Theosis", true, "Sword");
alert(soldier1.allegiance);
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
i know how to make objects but i dont know how to make the user input the data of the object and print onto the screen.
window.onload = submit;
function Soldier(allegiance,armor,weapon){
this.allegiance = "allegiance";
this.armor = armor;
this.weapon = weapon;
var soldier1 = document.getElementById("atext").value;
document.getElementById("soldier").innerHTML = " allegiance: " + soldier.allegiance + " <br/> " + " armor: " + soldier.armor + "</br>" + "Weapon(s): "+ soldier.weapon;
}
function submit(){
var submitButton = document.getElementById("button");
submitButton.onclick = Soldier;
}
<DOCTYPE HTML>
<html>
<head>
<script src = "objscript.js"> </script>
</head>
<body>
Allegiance: <input type ="text" id = "atext"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" value = "Submit"><br/>
<p id = "soldier"> </p>
</body>
</html>
I dont think im allowed to use push. im just suppose to make new soldiers by the user typing it in. i made the code a little better. now just need it to actually print
The solution:
HTML
Allegiance: <input type ="text" id = "allegiance"><br/><br/>
Armor: <input type ="text" id = "armor"><br/><br/>
Weapon(s): <input type ="text" id = "weapon"><br/><br/>
<input type = "button" id="button" onclick="hire()" value = "Submit"><br/>
<p id="output"></p>
JS
var soldiers = [];
function Soldier(allegiance, armor, weapon){
this.allegiance = allegiance;
this.armor = armor;
this.weapon = weapon;
this.doReport = function () {
return this.armor + ' and ' + this.weapon;
}
}
function doReport() {
output = "";
for(var i = 0; i < soldiers.length; i++) {
output += (i + 1) + ") " + soldiers[i].doReport() + "; ";
}
document.getElementById("output").innerHTML = output;
}
function hire() {
var soldier = new Soldier(
document.getElementById("allegiance").value,
document.getElementById("armor").value,
document.getElementById("weapon").value
);
soldiers.push(soldier);
doReport();
}
I added function hire() and bound it with submit button. A new soldier object is being pushed into the list of soldiers. Also I added doReport() method to Soldier and common doReport() function which makes a general report of all soldiers in the list. Right now, I call doReport() in the end of each hire(), but you can do it by clicking on some another button for example.

How to sort a multi dimensional array output in ascending order?

My code generates a two dimensional matrix when the OK is clicked. The code stores the data in the multidimensional array, but I am trying to add a sort function to the code which rearranges the code in ascending order using the 4th text box. Any suggestions on how I can do that ?
HTML Code
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<input type = "text" size = "1" id = "text1"/>
<input type = "text" size = "1" id = "text2"/>
<input type = "text" size = "1" id = "text3"/>
<input type = "text" size = "1" id = "text4"/><br>
<input type = "button" value = "Ok" id = "operation" onClick = "display()"/>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut">
<input type = "button" value = "By Result" id = "resultBut" onClick = "sort()"><br><br>
<div id="expressions">
</div>
</div>
</div>
Javascript Code
function display()
{
var arrayOne =[document.getElementById('text1').value,document.getElementById('text2').value,document.getElementById('text3').value,document.getElementById('text4').value ];
new_array=arrayOne.join(" ");
var para = document.createElement("p");
var t = document.createTextNode(new_array);
para.appendChild(t)
document.getElementById("expressions").appendChild(para);
}
function sort(){
var dispArr = [document.getElementById('text1').value,
document.getElementById('text2').value, document.getElementById('text3').value,document.getElementById('text4').value];
var myArray = [];
for(var i = 0 ; i < 1 ; i ++ ) {
myArray[i] = [];
for(var j = 0 ; j < 5 ; j++ )
{
myArray[i][j] = dispArr[j];
console.log(myArray[i][j]);
}
}
}
You would better keep the whole matrix in a memory variable, and add to that. Also consider that when the output is sorted, you must know how to get back to the original order also, so that the "As Entered" button still has the desired effect. So, it is better to have a display function that starts from scratch, empties the output and reproduces all the data in either entered or sorted order.
Here is how you could do that:
var matrix = []; // global value with all data
function addExpression() {
var arrayOne = [
document.getElementById('text1').value,
document.getElementById('text2').value,
document.getElementById('text3').value,
document.getElementById('text4').value
];
// add to matrix
matrix.push(arrayOne);
display(false);
}
function display(byResult) {
// Determine whether to sort or not:
var matrix2 = byResult ? sorted(matrix) : matrix;
// display each row:
var expressions = document.getElementById("expressions");
expressions.innerHTML = ''; // empty completely
matrix2.forEach( row => {
var para = document.createElement("p");
var t = document.createTextNode(row.join(" "));
para.appendChild(t)
expressions.appendChild(para);
});
}
function sorted(m){ // Create a copy, and sort that by last column
return m.slice().sort( (a, b) => a[3] - b[3] );
}
<div class="rightDiv">
<div id = "pastcalcblock">
<h3> PAST CALCULATIONS </h3>
<input type = "text" size = "1" id = "text1"/>
<input type = "text" size = "1" id = "text2"/>
<input type = "text" size = "1" id = "text3"/>
<input type = "text" size = "1" id = "text4"/><br>
<input type = "button" value = "Ok" id = "operation" onClick = "addExpression()"/>
<div id = "resultTab">
SORT<br>
<input type = "button" value = "As Entered" id = "enteredBut" onClick="display(false)">
<input type = "button" value = "By Result" id = "resultBut" onClick = "display(true)"><br><br>
<div id="expressions">
</div>
</div>
</div>
</div>

javascript: changing the name attribute dynamically

I have this script I'm working on and there's no errors on it but I want to add some functions on it like when I click the button it adds but I want the name attribute of the input text to be changed too.
Here's my script:
javascript:
var a = 1;
function add() {
var fContent = document.getElementById('1');
var sContent = document.getElementById('2');
if (a <= 10) {
a++;
var objTo = document.getElementById('m');
var divtest = document.createElement("div");
divtest.innerHTML = (sContent.innerHTML + a + fContent.innerHTML);
alert(divtest.innerHTML);
objTo.appendChild(divtest);
}
}
html:
<input type="button" onclick="add();" value="+" />
<div id="m">
<div id="1">
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">
</div>
<div id="2"></div>
</div>
OUTPUT:
2
<input type="text" name="f">
<input type="text" name="l">
<input type="text" name="m">
EXPECTED OUTPUT:
2
<input type="text" name="f2">
<input type="text" name="l2">
<input type="text" name="m2">
and so on...
You're not doing anything to change the name attributes. Trying to make those changes with html concatenation will get you into trouble. This will get you started:
(function() {
var a = 1;
// get a reference to the container
var container = document.getElementById("m");
// get a reference to the first row of input
var base = container.children[0];
document.querySelector("button").addEventListener("click", function(e) {
if(++a > 10) return;
// clone the first row of input
var clone = base.cloneNode(1);
// change the number text by setting the span's textContent
clone.children[0].textContent = a;
// set the names of the input fields
clone.children[1].name = "f" + a;
clone.children[2].name = "l" + a;
clone.children[3].name = "m" + a;
// add the new row to the container
container.appendChild(clone);
console.log(clone);
});
})();
<button type="button">+</button>
<div id="m">
<div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>
If you'd rather create the elements from scratch...
(function() {
var a = 1;
// get a reference to the container
var container = document.getElementById("m");
var input;
var span;
var div;
document.querySelector("button").addEventListener("click", function(e) {
if(++a > 10) return;
// create our div
div = document.createElement("div");
// create and append our span
span = document.createElement("span");
span.textContent = a;
div.appendChild(span);
// create and append inputs
["f","l","m"].forEach(function(n){
input = document.createElement("input");
input.name = n + a;
div.appendChild(input);
});
// append our div
container.appendChild(div);
console.log(div);
});
})();
<button type="button">+</button>
<div id="m">
<div><span>1</span><input type="text" name="f1"><input type="text" name="l1"><input type="text" name="m1"></div>
</div>

Categories

Resources