How to dynamically create variable with loop? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed last year.
Improve this question
How to re-write this code with loop?
var einput1 = document.querySelector("#email0").value;
var einput2 = document.querySelector("#email1").value;
var einput3 = document.querySelector("#email2").value;
and also how to access a specific variable from that loop? Thank You.
Edit:-
Here is demo-
//fuction to genrate email field
function emailGen() {
var quant = document.getElementById("quantity").value;
var container = document.getElementById("container");
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (a = 0; a < quant; a++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + a;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}
var form = document.getElementById("nameForm");
// event
form.addEventListener("submit", tableGen);
//function for table generator
function tableGen(e) {
e.preventDefault();
var body = document.getElementsByTagName("body")[0];
var table = document.createElement("table");
var tblbody = document.createElement("tbody");
var input1 = document.querySelector("#input1").value;
var quan = document.querySelector("#quantity").value;
//my question is here :-how to make this loop
var einput1 = document.querySelector("#email0").value;
var einput2 = document.querySelector("#email1").value;
var einput3 = document.querySelector("#email2").value;
//table rows loop
for (i = 0; i <= quan; i++) {
var tblrow = document.createElement("tr");
//table coloumn loop
for (j = 0; j < 1; j++) {
var tbldata = document.createElement("td");
if (i == 0 && j == 0) {
var pname = document.createTextNode(input1);
tbldata.appendChild(pname);
}
if (i == 1 && j == 0) {
var tname = document.createTextNode(einput1);
tbldata.appendChild(tname);
}
if (i == 2 && j == 0) {
var tname = document.createTextNode(einput2);
tbldata.appendChild(tname);
}
if (i == 3 && j == 0) {
var tname = document.createTextNode(einput3);
tbldata.appendChild(tname);
}
tblrow.appendChild(tbldata);
}
tblbody.appendChild(tblrow);
}
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton" onclick="emailGen()"> OK </button>
<div id="container"></div>
<br/>
<input type="submit" value="submit" onsubmit="tableGen()">
</form>
It only show table when input is 3 because declared variable are 3 (at the starting of question) and if I want to submit 1 or 2 field , it does not get submitted. if there is any way to create variable from loop and access it like I did here (einput1)
var tname = document.createTextNode(einput1);

You need to give the emails a name to submit them
Also I removed the onsubmit form the submit button. It does not belong there and can be removed. You have a submit event handler and that should do it
const container = document.getElementById("container");
document.getElementById("nameForm").addEventListener("submit", tableGen);
document.getElementById("okButton").addEventListener("click", emailGen);
//fuction to genrate email field
function emailGen() {
const quant = document.getElementById("quantity").value;
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (let i = 0; i < quant; i++) {
var emailGen = document.createElement("input");
emailGen.type = "email";
emailGen.id = "email" + i;
emailGen.name = "email" + i;
emailGen.placeholder = "Member's Email";
container.appendChild(emailGen);
}
}
//function for table generator
function tableGen(e) {
e.preventDefault();
const body = document.querySelector("body");
const table = document.createElement("table");
const tblbody = document.createElement("tbody");
const input1 = document.getElementById("input1").value;
const quan = document.getElementById("quantity").value;
const emails = container.querySelectorAll("[type=email]")
console.log(emails.length)
//table rows loop
for (let i = 0; i < quan; i++) {
const tblrow = document.createElement("tr");
for (let j = 0; j < emails.length; j++) {
const tblcell = document.createElement("td");
//table column loop
const pname = document.createTextNode(input1);
tblcell.appendChild(pname);
const tname = document.createTextNode(emails[j].value);
tblcell.appendChild(tname);
tblrow.appendChild(tblcell);
}
tblbody.appendChild(tblrow);
}
console.log
table.appendChild(tblbody);
body.appendChild(table);
table.setAttribute("border", "4");
}
<form id="nameForm">
<input type="text" id="input1" placeholder="Name"><br/>
<input type="number" id="quantity" name="quantity" placeholder="Total Members(max 10)" min="1" max="10">
<button type="button" id="okButton">OK</button>
<div id="container"></div>
<br/>
<input type="submit" value="submit">
</form>
Previous answer
document.getElementById("emailForm").addEventListener("submit", function(e) {
e.preventDefault(); // stop submit
const quan = +document.getElementById("quan").value
const addr = Array.from({length: quan}, (_, i) => `<input id="email${i}" type="email" placeholder="email${i}" />`)
this.innerHTML += addr.join('<br/>')
})
<form id="emailForm">
<input type="number" min=1 max=10 id="quan" /><br/>
</form>

You can use a loop & string interpolation to achieve the desired results.
The inputs array stores DOM nodes and then you can iterate over this to get the value as in the console.log below OR you can store the values in the input array if you don't want the DOM nodes anymore.
const quan = 3;
const inputs = Array.from({ length: quan }, (_, index) =>
document.querySelector(`#email${index}`)
);
console.log(inputs.map((inp) => inp.value));
<input id="email0" type="email" value="value0">
<input id="email1" type="email" value="value1">
<input id="email2" type="email" value="value2">

Related

How can I create a row which sums up the value of each column without knowing the row or column amount?

I have included my code below. I am creating a score keeping app and have created the basic score table where user can select player and round amount as well as add player names. I cant work out how to create a row to to sum every round for each player. I have tried several different ways but cant work it out. Any advice would be amazing! Have included code below.
<hr>
<body>
<div class="game-container">
<div class="row">
<div class="col-md-12">
<p>
<label>Enter number of players</label>
<br>
<input type="number" class="form-control" id="number-input" value="0" min="0">
<br>
<button id="makeTable">Go</button>
<table id="scoreTable">
</table>
<button id="addRound">Add Round</button>
<br>
<button id="totalValue">Sum Values</button>
</p>
</div>
</div>
</div>
</body>
<script>
/*Game page functionaility*/
let numberofRounds = 0;
// take number-input and make columns of it
function createColumns(){
const numberInput = document.getElementById('number-input');
const numberInputValue = numberInput.value;
const numberInputValueInt = parseInt(numberInputValue);
const scoreTable = document.getElementById('scoreTable');
topRow = document.createElement('tr');
topRow.setAttribute("id", "topRow");
scoreTable.appendChild(topRow);
const players = document.createElement('td');
players.innerHTML = "Players";
topRow.appendChild(players);
for(let i = 0; i < numberInputValueInt; i++){
const td = document.createElement('td');
td.innerHTML = `<input type="text" class="form-control" id="score-input">`;
topRow.appendChild(td);
}
document.getElementById('number-input').style.display = "none";
document.getElementById('makeTable').style.display = "none";
}
function addRound(){
const currentRound = +numberofRounds + 1;
numberofRounds = currentRound;
const roundNumber = "round_" + currentRound;
const numberInput = document.getElementById('number-input');
const numberInputValue = numberInput.value;
const numberInputValueInt = parseInt(numberInputValue);
const scoreTable = document.getElementById('scoreTable');
topRow = document.createElement('tr');
topRow.setAttribute("id", roundNumber);
scoreTable.appendChild(topRow);
const players = document.createElement('td');
players.innerHTML = currentRound;
topRow.appendChild(players);
for(let i = 0; i < numberInputValueInt; i++){
const td = document.createElement('td');
td.setAttribute("id", "round_"+currentRound+"_player_" + I);
td.innerHTML = `<input type="number" class="form-control" id="score-input"
value="0">`;
topRow.appendChild(td);
}
}
function addSumRow() {
if (!summedItems) {
const players = document.createElement('td');
}
}
// make event listener makeTable
document.getElementById("makeTable").addEventListener("click", function() {createColumns();});
document.getElementById("addRound").addEventListener("click", function() {addRound();});
document.getElementById("totalValue").addEventListener("click", function() {addSumRow();});
</script>

Javascript loop array for form validation

I have a table form with some rows, that are controlled by user. Meaning they can add as more as they want. Let's pretend user requested 5 rows and i need to check if they all have values.
function validateForm() {
var lastRowInserted = $("#packageAdd tr:last input").attr("name"); // gives me "packageItemName5"
var lastCharRow = lastRowInserted.substr(lastRowInserted.length - 1); // gives me 5
var i;
for (i = 1; i <= lastCharRow; i++) {
var nameValidate[] = document.forms["packageForm"]["packageItemName"].value;
if(nameValidate[i].length<1){
alert('Please fill: '+nameValidate[i]);
return false;
}
}
}
How can i receive packageItemName1 to 5 values in a loop so then I can use to validate them. Want the loop to process this code
var nameValidate[] = document.forms["packageForm"]["packageItemName1"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName2"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName3"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName4"].value;
var nameValidate[] = document.forms["packageForm"]["packageItemName5"].value;
Like this
const validatePackageItems = () => {
const nameValidate = $("form[name=packageForm] input[name^=packageItemName]"); // all fields with name starting with packageItemName
const vals = nameValidate.map(function() { return this.value }).get(); // all values
const filled = vals.filter(val => val.trim() !== ""); // all values not empty
console.log("Filled", filled, "= ", filled.length, "filled of", vals.length)
return filled.length === vals.length
};
$("[name=packageForm]").on("submit",(e) => {
if (!validatePackageItems()) {
alert("not valid");
e.preventDefault();
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="packageForm">
<input type="text" name="packageItemName1" value="one" /><br/>
<input type="text" name="packageItemName2" value="two" /><br/>
<input type="text" name="packageItemName3" value="" /><br/>
<input type="text" name="packageItemName4" value="four" /><br/>
<input type="submit">
</form>
You can use string interpolation to get the key dynamically:
for (let i = 1; i < 6; i++) {
const currentValue = document.forms.packageForm[`packageItemName${i}`]
console.log('current value:', currentValue)
}

Javascript Delete row with checkbox

Hi i'm a beginner and I'm trying to do a simple CRUD Car apps but i cannot delete row with my function deleteRow().
I've create a function call deleteRow i add a checkbox in every row with the createElement method and i'm setting the Id attribute using the setAttribute() method.In my function i'm trying to get to the checkbox to see if its checked and if so using the deleteRow method to delete the row.
function addRow() {
/* check if its empty */
var brandValue = document.getElementById("brand").value;
var modelValue = document.getElementById("model").value;
if (brandValue == "" || modelValue == "") {
return alert("Make sure you enter a brand and a model!")
}
/* Add a row */
"use strict";
var table = document.getElementById("table");
var row = document.createElement("tr");
var td1 = document.createElement("td");
var td2 = document.createElement("td");
var td3 = document.createElement("INPUT");
td3.setAttribute("type", "checkbox");
td3.setAttribute("id", "cb");
td1.innerHTML = document.getElementById("brand").value;
td2.innerHTML = document.getElementById("model").value;
row.appendChild(td1);
row.appendChild(td2);
row.appendChild(td3);
table.children[0].appendChild(row);
document.getElementById('brand').value = "";
document.getElementById('model').value = "";
}
var temp = 1;
function deleteRow() {
for (var j = temp - 2; j >= 0; j--) {
if (document.table.cb[j].checked) {
document.getElementById("table").deleteRow(j + 1);
}
}
}
<input type="text" id="brand" placeholder="Add a brand">
<input type="text" id="model" placeholder="Add a Model">
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
<table id="table">
<div class="tableDiv">
<tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
Right now nothing happen when i'm trying to delete and i have nothing in the browser console.
Thanks for your help.
Try this:
const $brand = document.getElementById("brand")
const $model = document.getElementById("model")
const $table = document.getElementById("table")
function addRow() {
/* check if its empty */
if ($brand.value == "" || $model.value == "") {
return alert("Make sure you enter a brand and a model!")
}
let $row = document.createElement("tr");
let $td1 = document.createElement("td");
let $td2 = document.createElement("td");
let $td3 = document.createElement("input");
$td3.setAttribute("type", "checkbox");
$td1.innerHTML = $brand.value;
$td2.innerHTML = $model.value;
$row.appendChild($td1);
$row.appendChild($td2);
$row.appendChild($td3);
$table.children[0].appendChild($row);
$brand.value = "";
$model.value = "";
}
function deleteRow() {
let checkboxs = $table.querySelectorAll("input[type='checkbox']:checked")
checkboxs.forEach(checkbox => checkbox.parentElement.remove())
}
<input type="text" id="brand" placeholder="Add a brand"></input>
<input type="text" id="model" placeholder="Add a Model"></input>
<button type="button" onClick="addRow()" id="add">Update</button>
<button type="button" onClick="deleteRow()" id="delete">Delete</button>
</div>
<table id="table">
<div class="tableDiv" <tr>
<th>Brands</th>
<th>Models</th>
<th>Select</th>
</tr>
</div>
</table>
for (var j = temp - 2; j >= 0; j--) { this loop never starts due to temp being 1.
1 - 2 = -1 so the loop condition (j >= 0) is never true.
Your main mistake is that you don't need to iterate anything, you can select the checked elements directly.
Try using document.querySelector("#table input[type='checkbox']:checked")
Another thing is that now you are assigning the same id to multiple elements. This should not be done, it can lead to unexpected behavior. Consider using class or custom attribute instead
let checkboxes = document.querySelectorAll('input[type="checkbox"]:checked');
checkboxes.forEach(checkbox => checkbox.parentElement.parentElement.remove());

Unable to retain the table values after refreshing the browser window

Created a form using html, javascript. After entering the fields, when i click submit button, it saves the user data in localstorage and updates the table rows dynamically. But once i refresh the browser, the table holding the information of all users is lost. I want to retain the table after refreshing the browser.
Click here to view screenshot of page Before refresh
Click here to view screenshot of page After refresh
JS Code :
var testObject = [];
var users = {};
function clear(){
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username,usermail,password,location,organization,gender){
if(username!="" && usermail!="" && password!="" && location!="" && organization!="" && gender!=""){
return true;
}
}
function removeDivChild(str)
{
if(document.getElementById(str).querySelector('p')){
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val,cdiv)
{
if(val=="" && document.getElementById(cdiv).querySelector('p')==null)
{
var node = document.createElement("P");
if(document.getElementById(cdiv).className=="textbox"){
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
}
else if(document.getElementById(cdiv).className=="radiobox"){
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if(val!="" && document.getElementById(cdiv).querySelector('p')!=null)
{
document.getElementById(cdiv).lastElementChild.remove();
}
}
function save(){
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if(document.getElementById("m").checked){
genval = document.getElementById("m").value;
}
if(document.getElementById("f").checked)
{
genval = document.getElementById("f").value;
}
if(IsValid(userval,eval,passval,locval,orgval,genval))
{
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
updateTable();
}
else
{
appendToDiv(userval,"userdiv");
appendToDiv(eval,"maildiv");
appendToDiv(passval,"passdiv");
appendToDiv(locval,"locdiv");
appendToDiv(orgval,"orgdiv");
appendToDiv(genval,"gendiv");
}
}
function updateTable(){
localStorage.setItem("user", JSON.stringify(testObject));
var usr = JSON.parse(localStorage.getItem('user'));
var i = testObject.length-1;
if(i==0){
var nodeh = document.createElement("tr");
var usernode = document.createElement("th");
var usertext = document.createTextNode("Username");
usernode.appendChild(usertext);
nodeh.appendChild(usernode);
var enode = document.createElement("th");
var etext = document.createTextNode("Email");
enode.appendChild(etext);
nodeh.appendChild(enode);
var pnode = document.createElement("th");
var ptext = document.createTextNode("Password");
pnode.appendChild(ptext);
nodeh.appendChild(pnode);
var lnode = document.createElement("th");
var ltext = document.createTextNode("Location");
lnode.appendChild(ltext);
nodeh.appendChild(lnode);
var onode = document.createElement("th");
var otext = document.createTextNode("Organization");
onode.appendChild(otext);
nodeh.appendChild(onode);
var gnode = document.createElement("th");
var gtext = document.createTextNode("gender");
gnode.appendChild(gtext);
nodeh.appendChild(gnode);
document.getElementById("t").appendChild(nodeh);
}
var noder = document.createElement("tr");
var nodeu = document.createElement("td");
var textu = document.createTextNode(usr[i].uname);
nodeu.appendChild(textu);
noder.appendChild(nodeu);
var nodee = document.createElement("td");
var texte = document.createTextNode(usr[i].email);
nodee.appendChild(texte);
noder.appendChild(nodee);
var nodep = document.createElement("td");
var textp = document.createTextNode(usr[i].pass);
nodep.appendChild(textp);
noder.appendChild(nodep);
var nodel = document.createElement("td");
var textl = document.createTextNode(usr[i].loc);
nodel.appendChild(textl);
noder.appendChild(nodel);
var nodeo = document.createElement("td");
var texto = document.createTextNode(usr[i].org);
nodeo.appendChild(texto);
noder.appendChild(nodeo);
var nodeg = document.createElement("td");
var textg = document.createTextNode(usr[i].gender);
nodeg.appendChild(textg);
noder.appendChild(nodeg);
document.getElementById("t").appendChild(noder);
clear();
}
HTML code :
<!DOCTYPE html>
<head>
<link rel="stylesheet" type="text/css" href="form.css">
</head>
<body>
<script src="check.js"></script>
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male"/> Male
<input type="radio" name="gender" id="f" value="female"/> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<table id="t" border="1">
</table>
</body>
</html>
After the back and forth in the comments on your question I decided to just create an example from your code sample. Most of it was untouched however I did add comments to the things that I did change.
// I moved the declaration of the testObject below to let the functions be created first
// so i can use teh new loadFromStorage function to create the object
var users = {};
// This is a new function I created
function loadFromStorage() {
// parse the 'user' object in local storage, if its empty return an empty array
return JSON.parse(localStorage.getItem('user')) || [];
}
function clear() {
// I didn't touch this function
document.getElementById("uname").value = "";
document.getElementById("email").value = "";
document.getElementById("pass").value = "";
document.getElementById("loc").value = "";
document.getElementById("org").value = "";
document.getElementById("m").checked = false;
document.getElementById("f").checked = false;
}
function IsValid(username, usermail, password, location, organization, gender) {
// I didn't touch this function
if (username != "" && usermail != "" && password != "" && location != "" && organization != "" && gender != "") {
return true;
}
}
function removeDivChild(str) {
// I didn't touch this function
if (document.getElementById(str).querySelector('p')) {
document.getElementById(str).lastElementChild.remove();
}
}
function appendToDiv(val, cdiv) {
// I didn't touch this function
if (val == "" && document.getElementById(cdiv).querySelector('p') == null) {
var node = document.createElement("P");
if (document.getElementById(cdiv).className == "textbox") {
var text = document.createTextNode("please enter " + document.getElementById(cdiv).lastElementChild.placeholder);
} else if (document.getElementById(cdiv).className == "radiobox") {
var text = document.createTextNode("please enter gender");
}
node.appendChild(text);
document.getElementById(cdiv).appendChild(node);
}
if (val != "" && document.getElementById(cdiv).querySelector('p') != null) {
document.getElementById(cdiv).lastElementChild.remove();
}
}
// Changes in this function
function save() {
var userval = document.getElementById("uname").value;
var eval = document.getElementById("email").value;
var passval = document.getElementById("pass").value;
var locval = document.getElementById("loc").value;
var orgval = document.getElementById("org").value;
var genval = "";
if (document.getElementById("m").checked) {
genval = document.getElementById("m").value;
}
if (document.getElementById("f").checked) {
genval = document.getElementById("f").value;
}
if (IsValid(userval, eval, passval, locval, orgval, genval)) {
users["uname"] = userval;
removeDivChild("userdiv");
users["email"] = eval;
removeDivChild("maildiv");
users["pass"] = passval;
removeDivChild("passdiv");
users["loc"] = locval;
removeDivChild("locdiv");
users["org"] = orgval;
removeDivChild("orgdiv");
users["gender"] = genval;
removeDivChild("gendiv");
testObject.push(users);
// Saving testObject to the persistent storage here because this is where it belongs
localStorage.setItem("user", JSON.stringify(testObject));
updateTable();
} else {
appendToDiv(userval, "userdiv");
appendToDiv(eval, "maildiv");
appendToDiv(passval, "passdiv");
appendToDiv(locval, "locdiv");
appendToDiv(orgval, "orgdiv");
appendToDiv(genval, "gendiv");
}
}
// Changes in this function
function updateTable() {
// pulled out the saving and the loading of user from localStorage here,
// everything should already be saved or loaded by the time we call
// this function.
// Also re-wrote this function because it was messy and hard to read, always remember you write code for humans not computers so slightly longer variable names that are descriptive are really good.
// get a reference to the table
var tbl = document.getElementById('t');
// remove all the child rows, except for the header
// CSS Selector explained:
// #t - find the table by the id (you used t)
// > tr > td - find all td's that are direct children of the t table
Array.prototype.forEach.call(document.querySelectorAll('#t > tr > td'), function(node) {
node.parentNode.removeChild( node );
})
// loop over all the 'users' in 'testObject'
for(var i = 0; i < testObject.length; i++){
// store a reference to the current object to make the code easier to read
var currentObject = testObject[i];
// create the TR
var tr = document.createElement('tr');
// Create the td's
var tdUserName = document.createElement('td');
var tdEmail = document.createElement('td');
var tdPassword = document.createElement('td');
var tdLocation = document.createElement('td');
var tdOrganization = document.createElement('td');
var tdGender = document.createElement('td');
// create the text nodes
var userName = document.createTextNode(currentObject.uname);
var email = document.createTextNode(currentObject.email);
var password = document.createTextNode(currentObject.pass);
var location = document.createTextNode(currentObject.loc);
var organization = document.createTextNode(currentObject.org);
var gender = document.createTextNode(currentObject.gender);
// add the elements to their containers
tdUserName.appendChild(userName);
tdEmail.appendChild(email);
tdPassword.appendChild(password);
tdLocation.appendChild(location);
tdOrganization.appendChild(organization);
tdGender.appendChild(gender);
// add the td's to the row
tr.appendChild(tdUserName);
tr.appendChild(tdEmail);
tr.appendChild(tdPassword);
tr.appendChild(tdLocation);
tr.appendChild(tdOrganization);
tr.appendChild(tdGender);
// add the row to the table
tbl.appendChild(tr);
}
// call your clear function
clear();
}
// load the object from storage
var testObject = loadFromStorage();
// populate the table
updateTable();
<div id="userdiv" class="textbox">
<input type="text" placeholder="Username" id="uname" name="Username">
</div>
<div id="maildiv" class="textbox">
<input type="text" placeholder="Email" id="email" name="Email">
</div>
<div id="passdiv" class="textbox">
<input type="text" placeholder="Password" id="pass" name="Password">
</div>
<div id="locdiv" class="textbox">
<input type="text" placeholder="Location" id="loc" name="Location">
</div>
<div id="orgdiv" class="textbox">
<input type="text" placeholder="Organization" id="org" name="Organization">
</div>
<div id="gendiv" class="radiobox">
<input type="radio" name="gender" id="m" value="male" /> Male
<input type="radio" name="gender" id="f" value="female" /> Female
</div>
<button id="submit" onclick="save()">Submit</button>
<!-- Added the header to the table, it isn't removed now when rebuilding it -->
<table id="t" border="1">
<thead>
<tr>
<td>Username</td>
<td>Email</td>
<td>Password</td>
<td>Location</td>
<td>Organization</td>
<td>Gender</td>
</tr>
</thead>
</table>
Here is a link to a JSFiddle because this example wont run properly because it accesses localStorage but is sandboxed. Working Example

Generate inputs using javascript

Number of M.C.Q questions:<input type="number" name="mcq" min="0"/></br>
</br>
Number of True/False questions:<input type="number" name="truefalse"
min="0"/></br></br>
<input type="submit" name="submit" value="Generate inputs"/>
Homepage
When i enter the number of mcq question and true/false and then submit i want to generate that many number of inputs so i can type my questions with four radio buttons for mcq and 2 radio buttons for true/false.
Is it possible in javascript?
If no how can i do it in php?
Something like this?
const mcq = document.getElementById('mcq')
const nb = document.getElementById('nb')
const button = document.getElementById('submit')
const res = document.getElementById('fields')
let qn, bn = 0;
button.addEventListener('click', function() {
while (res.firstChild) {
res.removeChild(res.firstChild);
};
qn = mcq.value || 0;
bn = nb.value || 0;
for (let i=0; i < qn; i++) {
let l = document.createElement('span');
l.innerText = 'Question ' + i;
let e = document.createElement('input');
e.setAttribute('id', 'q' + i);
res.appendChild(l);
res.appendChild(e);
for (let i=0; i < bn; i++) {
let b = document.createElement('input');
b.setAttribute('type', 'radio');
b.setAttribute('id', 'r' + i);
res.appendChild(b);
}
res.appendChild(document.createElement('br'));
};
})
Number of M.C.Q questions:<input type="number" name="mcq" id="mcq" min="0"/></br>
</br>
Number of True/False questions:<input type="number" id="nb" name="truefalse"
min="0"/></br></br>
<input type="submit" name="submit" id="submit" value="Generate inputs"/>
<div id='fields'></div>
All fields get unique id to enable further data gathering.

Categories

Resources