javascript array push not working - javascript

This is my jS code. When I press the button I want to add another element with a value of 1. Right now it is resetting the the array so I never get more than one element. What do I do here?
var x = document.getElementsByTagName('button');//return button array
var age_array = [];
smoker_array = [];
relation_array = [];
age = 0;
//add button clicked
x[0].addEventListener("click", function(){
/*
var age = document.getElementsByName("age")[0].value;//pull age from box
var relation = document.getElementsByName("rel")[0].value;//pull relation
let smoker = document.querySelector('[name=smoker').checked;
//check relation
if(relation === "")
{
alert("please select a realation");
}
//check to see if age < 0
if(age < 0 || age === " ")
{
alert("age not applicable");
}
*/
age_array.push(1);
alert(age_array.length);
});
/*function submit(age, relation, smoker)
{
age_array.push(age);
alert(age_array[0]);
alert(age_array[1]);
/*
x[1].addEventListener("click", function(){
var age = JSON.stringify(entry_age);
alert(entry_age[1]);
document.getElementbyClassName("debug").innerHTML = JSON.stringify(entry_relation);
document.getElementByClass("debug").innerHTML = JSON.stringfy(entry_smoker);
});
}
*/
here is the html code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Household builder</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Household builder</h1>
<div class="builder">
<ol class="household"></ol>
<form>
<div>
<label>Age
<input type="text" name="age">
</label>
</div>
<div>
<label>Relationship
<select name="rel">
<option value="">---</option>
<option value="self">Self</option>
<option value="spouse">Spouse</option>
<option value="child">Child</option>
<option value="parent">Parent</option>
<option value="grandparent">Grandparent</option>
<option value="other">Other</option>
</select>
</label>
</div>
<div>
<label>Smoker?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">add</button>
</div>
<div>
<button type="submit">submit</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="index.js"></script>
</body>
</html>

I don't know if it is the reason, but your code won't work in strict mode.
var age_array = [];
smoker_array = [];
relation_array = [];
should be:
var age_array = [],
smoker_array = [],
relation_array = [];
or:
var age_array = [];
var smoker_array = [];
var relation_array = [];

Hey guys thanks for the help. There seems to be something wrong with the HTML. I don't know what. I got the JS working using my own HTML, and I'm not allowed to change the HTML. Anyway thanks for all y'all help.
Marking this as answered

Related

Specify user input render location in javascript

[I'm simply trying to make a form that allows you to select which box the user's name and password will display in. The code I have works fine but I'm curious to see how it could be refactored to be less repetitive. I thought of using a JS object but I'm not sure how to go about that in this instance. Any help would be appreciated! Here is a link to the CodePen: (https://codepen.io/TOOTCODER/pen/yLeagRq)
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>Which Box?</title>
<style>
.square{
border: 1px solid black;
width: 15rem;
height: 15rem;
float: left;
}
#formContainer {
position: relative;
top: 16rem;
left: -45.5rem;
}
.boxTitle {
text-align: center;
margin-top: 1em;
}
.boxOutputContainer {
text-align: center;
}
</style>
</head>
<body>
<div class="square">
<h1 class="boxTitle">BOX1</h1>
<div class="boxOutputContainer">
<div id="b1NameOutput"></div>
<div id="b1PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX2</h1>
<div class="boxOutputContainer">
<div id="b2NameOutput"></div>
<div id="b2PasswordOutput"></div>
</div>
</div>
<div class="square">
<h1 class="boxTitle">BOX3</h1>
<div class="boxOutputContainer">
<div id="b3NameOutput"></div>
<div id="b3PasswordOutput"></div>
</div>
</div>
<div id="formContainer">
<form>
<label for="name">Name:</label>
<input required type="text" id="name">
<label for="name">Password:</label>
<input required type="text" id="password">
<label for="boxSelect">Which box?</label>
<select id="boxSelect">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<input type="submit" id="submitBtn">
</form>
</div>
<script>
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var b1NameOutput = document.querySelector("#b1NameOutput");
var b1PasswordOutput = document.querySelector("#b1PasswordOutput");
var b2NameOutput = document.querySelector("#b2NameOutput");
var b2PasswordOutput = document.querySelector("#b2PasswordOutput");
var b3NameOutput = document.querySelector("#b3NameOutput");
var b3PasswordOutput = document.querySelector("#b3PasswordOutput");
if(boxSelect.value == 1){
b1NameOutput.innerHTML = "<p>"+name.value+"</p>";
b1PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 2){
b2NameOutput.innerHTML = "<p>"+name.value+"</p>";
b2PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}else if(boxSelect.value == 3){
b3NameOutput.innerHTML = "<p>"+name.value+"</p>";
b3PasswordOutput.innerHTML = "<p>"+password.value+"</p>";
}});
</script>
</body>
</html>
I see someone beat me to the answer but here is another option that is easy to refactor.
var submitBtn = document.querySelector("#submitBtn");
var resetBtn = document.querySelector("#resetBtn");
submitBtn.addEventListener("click", function(){
event.preventDefault();
var name = document.querySelector("#name");
var password = document.querySelector("#password");
var boxSelect = document.querySelector("#boxSelect");
var nameId = `#b${boxSelect.value}NameOutput`;
var passwordId = `#b${boxSelect.value}PasswordOutput`;
var nameOutput = document.querySelector(nameId);
nameOutput.innerHTML = "<p>"+name.value+"</p>";
var passwordOutput = document.querySelector(passwordId);
passwordOutput.innerHTML = "<p>"+password.value+"</p>";
});

How to use functions in Javascript to bulid an interactive text?

I'm trying to build an interactive text with Javascript. I can do it by using a new function each element I create, but if I do that I'll have too many functions.
Could somebody tell me what is wrong with the following code and what I should do so it works?
Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1(peter)">Peter</button>
<button id="paul" onclick="includeName1(paul)">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2(mary)">Mary</button>
<button id="emma" onclick="includeName2(emma)">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").innerHTML;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
You need to wrap the names in apostrophes, at the moment you're trying to pass an object called 'peter' to the function. On the input, you need to use value instead of innerHtml.
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<div>
<p>Name:</p>
<button id="peter" onclick="includeName1('peter')">Peter</button>
<button id="paul" onclick="includeName1('paul')">Paul</button>
<p>Wife's name</p>
<button id="mary" onclick="includeName2('mary')">Mary</button>
<button id="emma" onclick="includeName2('emma')">Emma</button>
<p>How long have you been married?</p>
<input id="years" type="number" oninput="includeTime()">
</div>
<br/>
<div>
<p>My name is <span id="name1"></span>. I'm married to <span id="name2"></span>. We've been married for <span id="time"></span> years.
</p>
</div>
<script>
function includeName1(manName){
if (manName == "peter") {
document.getElementById("name1").innerHTML = "Peter";}
else if (manName == "paul") {
document.getElementById("name1").innerHTML = "Paul";
}
}
function includeName2(womanName){
if (womanName == "mary") {
document.getElementById("name2").innerHTML = "Mary";}
else if (womanName == "emma") {
document.getElementById("name2").innerHTML = "Emma";
}
}
function includeTime(){
var x = document.getElementById("years").value;
document.getElementById("time").innerHTML = x;
}
</script>
</body>
</html>
For the record...
this code should be more readable on this way:
const inTexts = document.getElementById('interractiv-texts')
, outText = document.getElementById('Out-Text')
, tVals = { man: '', wife: '', years: '' }
;
const setText = e =>
{
if (!e.target.matches('[data-part]')) return
tVals[e.target.dataset.part] = e.target.value
outText.textContent = `My name is ${tVals.man}, I'm married to ${tVals.wife}. We've been married for ${tVals.years} years.`
}
inTexts.oninput = setText
inTexts.onclick = setText
<div id="interractiv-texts">
<p>Name:</p>
<select data-part="man">
<option value="Peter">Peter</option>
<option value="Paul">Paul</option>
<option value="John">John</option>
</select>
<p>Wife's name</p>
<button value="Mary" data-part="wife">Mary</button>
<button value="Emma" data-part="wife">Emma</button>
<p>How long have you been married?</p>
<input data-part="years" type="number" >
</div>
<p id="Out-Text"></p>

Issue in Executing the jquery program for multi select list with (table)

Please Don't make it duplicate i have a code please refer that and let me where i'm doing wrong Hello guys i have program which deals with the multi select list where I have implemented such functionality where user can Add or Remove item from left side list to right side list ("<" and ">").This Totally works fine Again i have added a Table which contains the right side (selected list values) for this code is :
HTML: In this "sourceHeaderFields" contains the list where we are selecting list adding to the "sourceHeaderFields"
<h2><strong>Select features from Seed data:</strong> </h2>
<select id="sourceHeaderFields" name="sourceHeaderFields" multiple="multiple"
style="width:210Px;height:150px;margin-left: 100px;">
</select>
<select id="sourceHeaderFields" name="targetHeaderFields" multiple="multiple"
style="width:210Px; height:150px">
</select>
<br>
<input type="button" id="leftall" value="<<" style="margin-left: 250px;"/>
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<br></br>
<h2> <strong> Default Values for the Selected Headers: </strong> </h2>
<table id="defaultValuesTable">
</table>
JS
$(function () {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
$('#left').click(function () {
selectedValue1 = $('#targetHeaderFields').remove(':selected').val()
//console.log(selectedValue1);
moveItems('#targetHeaderFields', '#sourceHeaderFields');
$("#defaultValuesTable").remove().append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
});
$('#right').on('click', function () {
selectedValue = $('#sourceHeaderFields').find(':selected').val()
console.log(selectedValue);
moveItems('#sourceHeaderFields', '#targetHeaderFields');
debugger;
//Populate the table with the field
$("#defaultValuesTable").append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
});
Multilist works fine but problem is this line:for table list****Please go this for live code working: https://jsfiddle.net/8jbp47zq/ not sure how to paste a csv file to get the list
$("#defaultValuesTable").remove().append("<tr id='"+selectedValue+"'><td>"
+selectedValue+"</td><td><input type='text'></tr>");
Here when i'm adding anything its adding a text bar for the table with accoresponding list name but when i'm removing its not removing one by one at once its remove all...i want to remove the table list one by one not at once for that i have tried many way:
//$("#defaultValuesTable").remove(id="+selectedValue1+");
and
//$("#defaultValuesTable").children("tr").remove();
and
//$("#defaultValuesTable").remove().append(id="+selectedValue1+");
none of these worked please help..If you guys need more info please tell me ill give...I have added a pic of web UI please refer that...thnx
There was an issue with the remove process. I've updated the code.
//A drop-down list
$(document).ready(function() {
for (var i = 1970; i <= 2018; i++) {
var fromYearSelect = document.getElementById("fromYear");
var toYearSelect = document.getElementById("toYear");
var option = document.createElement("OPTION");
fromYearSelect.options.add(option);
option.text = i;
option.value = i;
var option2 = document.createElement("OPTION");
toYearSelect.options.add(option2);
option2.text = i;
option2.value = i;
}
});
$(function() {
function moveItems(origin, dest) {
$(origin).find(':selected').appendTo(dest);
}
function moveAllItems(origin, dest) {
$(origin).children().appendTo(dest);
}
$('#left').click(function() {
debugger;
selectedValue1 = $('#targetHeaderFields').remove(':selected').val()
//console.log(selectedValue1);
moveItems('#targetHeaderFields', '#sourceHeaderFields');
debugger; // fixed below line.
$('#'+selectedValue1, "#defaultValuesTable").remove();
//$("#defaultValuesTable").children("tr").remove();
//$("#defaultValuesTable").remove().append(id="+selectedValue1+");
// $("#defaultValuesTable").remove().append("<tr id='" + selectedValue + "'><td>" +
// selectedValue + "</td><td><input type='text'></tr>");
});
$('#right').on('click', function() {
selectedValue = $('#sourceHeaderFields').find(':selected').val()
console.log(selectedValue);
moveItems('#sourceHeaderFields', '#targetHeaderFields');
debugger;
//Populate the table with the field
$("#defaultValuesTable").append("<tr id='" + selectedValue + "'><td>" +
selectedValue + "</td><td><input type='text'></tr>");
});
$('#leftall').on('click', function() {
moveAllItems('#targetHeaderFields', '#sourceHeaderFields');
});
$('#rightall').on('click', function() {
moveAllItems('#sourceHeaderFields', '#targetHeaderFields');
});
$('#populateHeaderFields').on('click', function() {
alert("Inside populate list");
var files = ('#source_fileName').files;
alert("Files Count - " + files);
});
$('#upload-form').on('change', function(evt) {
//alert('File content changed');
debugger;
var filesCount = evt.target.files.length;
for (i = 0; i < filesCount; i++) {
var file = evt.target.files[i];
if (file) {
var reader = new FileReader();
/*
reader.onload = function(e) {
var contents = e.target.result;
var ct = reader.result;
var words = ct.split(' ');
}
reader.readAsText(file);
*/
// Read our file to an ArrayBuffer
reader.readAsArrayBuffer(file);
// Handler for onloadend event. Triggered each time the reading operation is completed (success or failure)
reader.onloadend = function(evt) {
// Get the Array Buffer
var data = evt.target.result;
// Grab our byte length
var byteLength = data.byteLength;
// Convert to conventional array, so we can iterate though it
var ui8a = new Uint8Array(data, 0);
// Used to store each character that makes up CSV header
var headerString = '';
// Iterate through each character in our Array
for (var i = 0; i < byteLength; i++) {
// Get the character for the current iteration
var char = String.fromCharCode(ui8a[i]);
// Check if the char is a new line
if (char.match(/[^\r\n]+/g) !== null) {
// Not a new line so lets append it to our header string and keep processing
headerString += char;
} else {
// We found a new line character, stop processing
break;
}
}
//Iterate through the list and populate the select element..
$.each(headerString.split(","), function(i, e) {
$("#sourceHeaderFields").append($("<option>", {
text: e,
value: e
}));
});
// if len(headerString)!= 1{
// alert("headerString Donot match");
// }else{
console.log(headerString);
console.log("Next Read");
};
} else {
alert("Failed to load file");
}
}
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title> upload </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<link href="https://bootswatch.com/4/solar/bootstrap.min.css" rel="stylesheet" type="text/css">
</head>
<body>
<div class="container">
<div class="jumbotron">
<div class="mx-auto" style="width:500px;">
<h1>Large Data Generation</h1>
</div>
</div>
<form id="upload-form" action="{{ url_for('upload') }}" method="POST" enctype="multipart/form-data">
<div id="file-selector">
<p>
<strong>Source File: </strong>
<input id="source_fileName" type="file" name="source_fileName" accept="csv/*" multiple style="
margin-left: 10px;" />
</p>
</div>
<br>
<strong>Location Type:</strong>
<input type="radio" name="target" value="BrowserDownload" checked>Browse Local
<input type="radio" name="target" value="dumpToS3"> S3 Remote
<br> </br>
<h2><strong>Select features from Seed data:</strong> </h2>
<select id="sourceHeaderFields" name="sourceHeaderFields" multiple="multiple" style="width:210Px;height:150px;margin-left: 100px;">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<select id="targetHeaderFields" name="targetHeaderFields" multiple="multiple" style="width:210Px; height:150px">
</select>
<br>
<input type="button" id="leftall" value="<<" style="margin-left: 250px;" />
<input type="button" id="left" value="<" />
<input type="button" id="right" value=">" />
<input type="button" id="rightall" value=">>" />
<br />
<br></br>
<h2><strong>Default Values for the Selected Headers:</strong></h2>
<table id="defaultValuesTable">
</table>
<br>
<div>
<br>
</div>
<div id="div_records">
<strong>Record Count: </strong>
<input id="records" type="text" name="records" value="1000" style="margin-left: 5px;">
<br> <br> <br>
<strong>From Year: </strong>
<select id="fromYear" name="fromYear" style="margin-left: 30px;"></select>
<strong style="margin-left:20px">To Year: </strong>
<select id="toYear" name="toYear" style="margin-left: 5px;"></select>
<br></br>
</div>
<br></br>
<input type="submit" value="Generate Data" id="upload-button">
</form>
</div>
</body>
Remove multiple/all rows one by one from a table with delay use below code.
var i=0;
$('#defaultValuesTable tr').each(function() {
var dly=200;
$(this).delay(i*dly).queue(function(){
$(this).remove();
});
i++;
});
Change value of dly to increase/decrease delay

Validate form, Assign form input to strings and display them in JavaScript

So I've been cracking at this code and can't figure out what's going on.
Basically, I must validate this form, and assign each input into a string, then display it later. Right now, I can't even grasp at the validation because it just won't work, when I click the "adicionar" button the page simply refreshes. It should show an alert if the forms are empty, and for the age input, it should alert if it's not numeric or if it's <= 0.
Here's the JavaScript and HTML:
window.onload = function code(){
function validarForm()
{
var company = document.getElementById('empresa').value;
var name = document.getElementById('nome').value;
var team = document.getElementById('time').value;
var age = document.getElementById('idade').value;
if (company == '' || company == null) {
alert("O campo Empresa é obrigatório!");
return false;
}
if (name == '') {
alert("O campo Nome é obrigatório!");
return false;
}
if (team == '') {
alert("O campo Time é obrigatório!");
return false;
}
if (isNaN(age) || age <= 0) {
alert("Escreva um número maior que 0!");
return false;
}
}
document.getElementsByClassName("add").onclick = function() {validateForm()};
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cadastro de Desenvolvedores</title>
<style>
.debug {
font-family: monospace;
border: 1px solid black;
padding: 10px;
display: none;
}
</style>
</head>
<body>
<h1>Cadastros de desenvolvedores</h1>
<div class="cadastro">
<ol class="desenvolvedores"></ol>
<form>
<div>
<label>Empresa
<input type="text" name="empresa">
</label>
</div>
<div>
<label>Nome
<input type="text" name="nome">
</label>
</div>
<div>
<label>Idade
<input type="text" name="idade">
</label>
</div>
<div>
<label>Time
<select name="time">
<option value="">---</option>
<option value="front">Frontend</option>
<option value="back">Backend</option>
<option value="infra">Infraestrutura</option>
<option value="telecon">Telefonia</option>
<option value="outro">Outro</option>
</select>
</label>
</div>
<div>
<label>Tecnologias
<select multiple name="tec">
<option value="js">Javascript</option>
<option value="php">PHP</option>
<option value="java">Java</option>
<option value="ruby">Ruby</option>
<option value="python">Python</option>
<option value="perl">Perl</option>
</select>
</label>
</div>
<div>
<label>Estágio?
<input type="checkbox" name="smoker">
</label>
</div>
<div>
<button class="add">adicionar</button>
</div>
<div>
<button type="submit">enviar</button>
</div>
</form>
</div>
<pre class="debug"></pre>
<script type="text/javascript" src="./index.js"></script>
</body>
</html>
Also, something to note is that the assignment requires that the HTML file should not be changed directly (only being able to make changes via javascript), and no JavaScript libraries are allowed (not even jQuery). Sorry some of the code is not in English, because i'm Brazilian.
getElementsByClassName will return an array of items. change class to id="add" to get the click function to work
OK. Where to start!
As Kody says, getElementsByClassName returns an array of elements. As there is only one element with that class you can use
document.getElementsByClassName("add")[0].onclick = function() {return validarForm()};
also note that the function is validarForm() not validateForm() and you need to add "return" otherwise it will submit.
You can't use getElememtById to get the values of the textboxes as they don't have an Id set, just a name. so you would have to get the inputs using
document.getElementsByTagName('input')
Note that this too returns an array of elements for you to work with.

Javascript dynamic input fields on a dynamic inputfield

I added a field for text input between the 2 Drop downs if Option number 3 is selected, the text box will appear.
This new text box should get numbers from the User and add new text fields under the Element for options.
For example: if the user adds the number 3 in the text box the radio button created, 3 new text boxes will show up under the Element row and look like this:
Option 1 _____________
Option 2 _____________
Option 3 _____________
// Funkcija za pravljenje Elemenata
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=question + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
      
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>
The issue is that you are executing the code only one time.
Put it inside a loop.
Here, I made a loop to execute the same code x times where x is the number user entered in the form
Check the snippet
var i = 0;
var a = 1;
function mojaFunkcija() {
var type1 = document.getElementById('type1').value;
var type2 = document.getElementById('type2').value;
var question = document.getElementById('question').value;
var i=0;
while(i<question){
var counter = 'Element';
counter+= a;
var prviElement=document.createElement('span');
prviElement.textContent= counter + ':' +' ';
document.body.appendChild(prviElement);
var pitanje= document.createElement('span');
var unos='unos';
unos += i;
pitanje.id=unos;
pitanje.textContent=(i+1) + ' ';
document.body.appendChild(pitanje);
var tip1 = document.createElement("input");
var element='element';
element += i;
tip1.id=element;
if (type1=='textbox') {
tip1.type=type2
} else {
tip1.type=type1
}
document.body.appendChild(tip1);
var linija1= document.createElement("br");
document.body.appendChild(linija1);
var linija2= document.createElement("br");
document.body.appendChild(linija2);
i++;
a++;
}
}
function AddTextBox(elm) {
var v = elm.value;
var iCounter = elm.id.replace('type1', '');
if (v == 'radio') {
var textbox = document.createElement('input');
textbox.type = 'text';
textbox.id = 'txtSecond' + iCounter;
elm.parentNode.insertBefore(textbox, elm.nextSibling);
} else {
//Ovaj kod ce da izbrise Textbox u slucaju da se izabere druga opcija.
var rmv = document.getElementById('txtSecond' + iCounter);
if (rmv != undefined) {
rmv.remove();
}
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" type="text/css" href="pepo.css">
<meta charset="UTF-8">
<script src="basa.js"></script>
<title>OnlineForms</title>
</head>
<body>
<!--Ovaj kod je za Main Page-->
<Main class="kocka">
<div align="left">
<input type="button" class="dropbtn" value="Administration" onClick="window.location.reload();return false;"/>
      
<button class="dropbtn" id="getAllButton">Forms</button>
</div>
<br>
<div align="left">
<input type="number" id="key" class="dropbtn" Placeholder="Type the key value"/>
<button class="dropbtn" id="getButton"> Search </button>
<br>
<br>
</div>
</Main>
<!--Ovaj kod je za Elemente-->
<div id="element" class="hide">
<h1>Element <input type="text" class="dropbtn" id="question" value="" Placeholder="Type your question here"/>
<select title="ddmenu" class="dropbtn" id="type1" onChange="AddTextBox(this)">
<option selected disabled hidden value="Please select">Please select</option>
<option value="textbox">textbox</option>
<option value="checkbox">checkbox</option>
<option value="radio">radio button</option>
</select>
<select title="ddmenu" class="dropbtn" id="type2">
<option selected disabled hidden value="Please select">Please select</option>
<option value="none">none</option>
<option value="mandatory">mandatory</option>
<option value="number">numeric</option>
</select>
</h1>
<input type="button" id="adddugme" class="dropbtn2" value="Add" onclick="mojaFunkcija()"/>
<br>
<br>
<button id="addButton" class='dropbtn'>Save</button>
</div>
<br>
<br>
<div id="status"></div>
<br>
<div id="status2"></div>
</body>
</html>
I think I understand what you're trying to achieve. It seems you're already able to reference the inputbox you want the value from because you're removing it in your AddTextBox function. In which case you can use similar code to loop depending on that value. Something like this:
var cnt = document.getElementById('txtSecond' + iCounter);
if (cnt != undefined && Number.isInteger(parseInt(cnt.value))) {
// loop to create options
}
Read about the Conditional (Ternary) Operator
then simplify your js:
option ? option1 : option2
as for the display, I would use:
if (option === 'option1'){
$('option2).hide() // or show
}
a little jquery in there, and so forth.

Categories

Resources