Unable to remove previous input - javascript

I have an input that when a number is entered, JavaScript creates that number of additional inputs.
This code works but when I set a new number, the previous inputs aren't deleted. It just generates more input fields.
My code:
$("#child").change(function () {
if($("#child").val() > 0){
var num = $(this).val();
var i =1
console.log(num)
for(i ; i<=num ; i++){
var div=document.createElement("div");
div.className="form-group col-md-4";
var lbel = document.createElement("label");
var text = document.createTextNode("سن فرزند"+ " " + i);
lbel.appendChild(text);
lbel.className="text-form"
div.appendChild(lbel);
var inp = document.createElement("input");
inp.name="child"+i;
inp.className="form-control";
div.appendChild(inp);
document.getElementById('chil').appendChild(div);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-4">
<label class="text-form"> تعداد فرزندان </label>
<input type="text" class="form-control" placeholder="تعداد فرزندان "id="child">
</div>
<div id="chil" class="row py-4">
</div>

Here's a fiddle
$("#child").change(function() {
if ($("#child").val() > 0) {
var num = $(this).val();
var i = 1
console.log(num)
$('#chil').empty(); // Just empty your div
for (i; i <= num; i++) {
var div = document.createElement("div");
div.className = "form-group col-md-4";
var lbel = document.createElement("label");
var text = document.createTextNode("سن فرزند" + " " + i);
lbel.appendChild(text);
lbel.className = "text-form"
div.appendChild(lbel);
var inp = document.createElement("input");
inp.name = "child" + i;
inp.className = "form-control";
div.appendChild(inp);
document.getElementById('chil').appendChild(div);
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-md-4">
<label class="text-form"> تعداد فرزندان </label>
<input type="text" class="form-control" placeholder="تعداد فرزندان " id="child">
</div>
<div id="chil" class="row py-4">
</div>

<div class="form-group col-md-4">
<label class="text-form"> تعداد فرزندان </label>
<input type="text" class="form-control" placeholder="تعداد فرزندان " id="child">
</div>
<div id="chil" class="row py-4">
</div>
$("#child").change(function() {
if ($("#child").val() > 0) {
var num = $(this).val();
var i = 1
console.log(num)
$('#chil').empty()
for (i; i <= num; i++) {
var div = document.createElement("div");
div.className = "form-group col-md-4";
var lbel = document.createElement("label");
var text = document.createTextNode("سن فرزند" + " " + i);
lbel.appendChild(text);
lbel.className = "text-form"
div.appendChild(lbel);
var inp = document.createElement("input");
inp.name = "child" + i;
inp.className = "form-control";
div.appendChild(inp);
document.getElementById('chil').appendChild(div);
}
}
});
Codepen

Related

new input replace Instead of append

Here is the html that I wrote for program
It's working but append is not working.
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6 justify-content-center">
<span>Full Name :</span>
<input id="name" type="name" class="d-flex mb-3">
<span>Email :</span>
<input id="email" type="email" name="email" class="d-flex mb-3">
<span>Comment :</span>
<input id="comment" type="text" class="d-flex mb-3">
<button id="btn" class="mt-3">Submit</button>
</div>
<div class="col-md-6">
<p id="demo"></p>
</div>
</div>
</div>
name and comment are inputs.
I type some text but append doesn't working and the new text that entered replace the first one.
function SubmitComment(name, comment) {
let newComment = censor(comment)
for (let i = 0; i < name.length; i++) {
let demo = $("#demo");
demo.html("")
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "swan") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Am not sure why your looping the name property, but here is a working example!
function Submit() {
SubmitComment($('.name'), $('.comment'));
}
function SubmitComment(name, comment) {
let newComment = censor(comment)
let demo = $("#demo");
demo.html("")
for (let i = 0; i < name.length; i++) {
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "kilt") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="name" />
<input class="comment" />
<button onClick="Submit()">Submit</button>
<div id="demo"></div>

problem with loop in google web script app

Good night, how are you?
I created a form, that before the information is inserted in the spreadsheets, the data goes to an HTML table, where you can delete or edit it before sending the data, so far so good,
the problem that I tried to create a loop to go clicking several times until all the data in the table ends, the problem that when I run the loop there is an error that all the data cannot go to the spreadsheet.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
</head>
<body id="pagina">
<br>
<div class= "container">
<div class="row">
<div class="input-field col s12 l4">
<input id="saiDesc" type="text" class="autocomplete" class="validate" required>
<!--<label for="saiDesc" class="active">DESCRIÇÃO DO PRODUTO</label>-->
<label>PRODUTO</label><label class="validation-error hide" id="fullNameValidationError">This field is required.</label>
</div>
<div class="input-field col s6 l1">
<input id="saiCod" type="text" class="validate" required>
<label for="saiCod">CÓDIGO</label>
</div>
<div class="input-field col s6 l1">
<input id="saiQtd" type="text" class="validate" required>
<label for="saiQtd">QUANTIDADE</label>
</div>
<div class="input-field col s6 l1">
<input id="saiVlr" type="text" class="validate" required>
<label for="saiVlr">VALOR</label>
</div>
<div class="input-field col s6 l1">
<input id="saiTotal" type="text" class="validate" required>
<label for="saiTotal">VALOR TOTAL</label>
</div>
<div class="input-field col s12 l4">
<input id="saiObs" type="text" class="validate" required>
<label for="saiObs">OBSERVAÇÃO</label>
</div>
</div> <!-- Fecha Row -->
<div class="row">
<div class="input-field col s6 l1">
<input disabled id="saiTotalizador" type="text">
<label for="saiTotalizador">TOTAL</label>
</div>
<div class="center-align">
<button id="teste" onclick="onFormSubmit(); sum();" class="left waves-effect waves-light btn red darken-2"><i class="material-icons left">add</i>ADD</button>
<button id="teste" onclick="preencher();" class="center waves-effect waves-light btn blue darken-2"><i class="material-icons left">add</i>preencher</button>
<button id="registrar2" class="right waves-effect waves-light btn blue-grey darken-2"><i class="material-icons left">send</i>REGISTER ALL</button>
</div> <!-- Fecha Row -->
</div>
<hr>
<!--<div class="form-action-buttons">
<input type="submit" onclick="onFormSubmit();"value="Enviar">
</div>-->
<td>
<table class="list" id="employeeList">
<thead>
<tr>
<th>PRODUTO</th>
<th>CÓD INT.</th>
<th>QUANT.</th>
<th>VALOR<br/>UNIT.</th>
<th>VALOR<br/>TOTAL</th>
<th>OBS.</th>
<th></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div> <!-- Fecha Conatainer -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/js/materialize.min.js"></script>
<script>
var selectedRow = null
function onFormSubmit() {
if (validate()) {
var formData = readFormData();
if (selectedRow == null)
insertNewRecord(formData);
else
updateRecord(formData);
resetForm();
}
}
function readFormData() {
var formData = {};
formData["saiDesc"] = document.getElementById("saiDesc").value;
formData["saiCod"] = document.getElementById("saiCod").value;
formData["saiQtd"] = document.getElementById("saiQtd").value;
formData["saiVlr"] = document.getElementById("saiVlr").value;
formData["saiTotal"] = document.getElementById("saiTotal").value;
formData["saiObs"] = document.getElementById("saiObs").value;
return formData;
}
function insertNewRecord(data) {
var table = document.getElementById("employeeList").getElementsByTagName('tbody')[0];
var newRow = table.insertRow(table.length);
cell1 = newRow.insertCell(0);
cell1.innerHTML = data.saiDesc;
cell2 = newRow.insertCell(1);
cell2.innerHTML = data.saiCod;
cell3 = newRow.insertCell(2);
cell3.innerHTML = data.saiQtd;
cell4 = newRow.insertCell(3);
cell4.innerHTML = data.saiVlr;
cell5 = newRow.insertCell(4);
cell5.innerHTML = data.saiTotal;
cell6 = newRow.insertCell(5);
cell6.innerHTML = data.saiObs;
cell6 = newRow.insertCell(6);
cell6.innerHTML = `<a onClick="onEdit(this)" id="testeEdit" class="btn-floating blue"><i class="material-icons left">edit</i></a>
<a onClick="onDelete(this)" id="testedelete" class="btn-floating red" ><i class="material-icons left">delete</i></a>`;
}
function resetForm() {
document.getElementById("saiDesc").value = "";
document.getElementById("saiCod").value = "";
document.getElementById("saiQtd").value = "";
document.getElementById("saiVlr").value = "";
document.getElementById("saiTotal").value = "";
document.getElementById("saiObs").value = "";
selectedRow = null;
}
function onEdit(td) {
selectedRow = td.parentElement.parentElement;
document.getElementById("saiDesc").value = selectedRow.cells[0].innerHTML;
document.getElementById("saiCod").value = selectedRow.cells[1].innerHTML;
document.getElementById("saiQtd").value = selectedRow.cells[2].innerHTML;
document.getElementById("saiVlr").value = selectedRow.cells[3].innerHTML;
document.getElementById("saiTotal").value = selectedRow.cells[4].innerHTML;
document.getElementById("saiObs").value = selectedRow.cells[5].innerHTML;
M.updateTextFields();
}
function updateRecord(formData) {
selectedRow.cells[0].innerHTML = formData.saiDesc;
selectedRow.cells[1].innerHTML = formData.saiCod;
selectedRow.cells[2].innerHTML = formData.saiQtd;
selectedRow.cells[3].innerHTML = formData.saiVlr;
selectedRow.cells[4].innerHTML = formData.saiTotal;
selectedRow.cells[5].innerHTML = formData.saiObs;
}
function onDelete(td) {
// if (confirm('Are you sure to delete this record ?')) {
row = td.parentElement.parentElement;
document.getElementById("employeeList").deleteRow(row.rowIndex);
resetForm();
//}
}
function validate() {
isValid = true;
if (document.getElementById("saiDesc").value == "") {
isValid = false;
document.getElementById("fullNameValidationError").classList.remove("hide");
} else {
isValid = true;
if (!document.getElementById("fullNameValidationError").classList.contains("hide"))
document.getElementById("fullNameValidationError").classList.add("hide");
}
return isValid;
}
function sum() {
var table = document.getElementById("employeeList");
var sumVal = 0;
for(var i = 1; i < table.rows.length; i++)
sumVal = sumVal + parseFloat(table.rows[i].cells[4].innerHTML.replace(",", "."));
document.getElementById("saiTotalizador").value = sumVal;
M.updateTextFields();
}
function preencher(){
document.getElementById("saiDesc").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiCod").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiQtd").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiVlr").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiTotal").value = Math.floor((Math.random() * 10) + 1);
document.getElementById("saiObs").value = Math.floor((Math.random() * 10) + 1);
M.updateTextFields();
}
document.getElementById("registrar2").addEventListener("click",registrarTudo2);
function registrarTudo2(){
var linhas = employeeList.querySelectorAll("tr").length-1;
for (var i = 0; i < linhas; i ++){
document.getElementById("testeEdit").click();
var userInfo = {};
userInfo.saiDesc = document.getElementById("saiDesc").value;
userInfo.saiCod = document.getElementById("saiCod").value;
userInfo.saiQtd = document.getElementById("saiQtd").value;
userInfo.saiVlr = document.getElementById("saiVlr").value;
userInfo.saiTotal = document.getElementById("saiTotal").value;
userInfo.saiObs = document.getElementById("saiObs").value;
google.script.run.registrar(userInfo);
document.getElementById("testedelete").click();
};
};
</script>
</body>
</html>
Gas:
function registrar(userInfo){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/1XVICy3RPRRUPtyXtgSi9Ab7iaOOODM6zkJ3Fq4T-h_M/edit#gid=0");
var ws = ss.getSheetByName("Página1");
ws.appendRow([userInfo.saiDesc,
userInfo.saiCod,
userInfo.saiQtd,
userInfo.saiVlr,
userInfo.saiTotal,
userInfo.saiObs
]);
}
note: if I take the loop and click 2x, 3x, 15x, the register button runs the script right.
just with the loop it gives the error.
How about this modification?
Modification points:
I think that the reason of your issue is that google.script.run is run with the asynchronous process. But in your case, the method of appendRow is used in the for loop at Google Apps side. In this case, the process cost will be high. So in this answer, I would like to propose the following flow.
Retrieve all values of userInfo and put them to an array.
Send the array to Google Apps Script side using google.script.run.
At Google Apps Script side, convert the array for putting to Spreadsheet and put the values.
When above points are reflected to your script, it becomes as follows.
Modified script:
HTML&Javascript side:
Please modify registrarTudo2() as follows.
function registrarTudo2(){
var values = []; // Added
var linhas = employeeList.querySelectorAll("tr").length-1;
for (var i = 0; i < linhas; i ++){
document.getElementById("testeEdit").click();
var userInfo = {};
userInfo.saiDesc = document.getElementById("saiDesc").value;
userInfo.saiCod = document.getElementById("saiCod").value;
userInfo.saiQtd = document.getElementById("saiQtd").value;
userInfo.saiVlr = document.getElementById("saiVlr").value;
userInfo.saiTotal = document.getElementById("saiTotal").value;
userInfo.saiObs = document.getElementById("saiObs").value;
values.push(userInfo); // Added
document.getElementById("testedelete").click();
}
google.script.run.registrar(values); // Added
}
Google Apps Script side:
Please modify registrar() as follows.
function registrar(values){
var ss = SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/###/edit#gid=0");
var ws = ss.getSheetByName("Página1");
var v = values.map(userInfo => [userInfo.saiDesc,userInfo.saiCod,userInfo.saiQtd,userInfo.saiVlr,userInfo.saiTotal,userInfo.saiObs]); // Added
ws.getRange(ws.getLastRow() + 1, 1, v.length, v[0].length).setValues(v); // Added
}
Please set the URL of your Spreadsheet to SpreadsheetApp.openByUrl("https://docs.google.com/spreadsheets/d/###/edit#gid=0").
References:
Class google.script.run
setValues(values)

Input's onclick event is not responding when i declare the name="band[ ]"

I want to limit the selection of checkboxes through limit_checkbox() function but when i declare the name of input to an array it is not responding. The error shows " Uncaught ReferenceError: limit_checkbox is not defined at HTMLInputElement.onclick"
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>
<script>
var a, b = false;
function limit_checkbox(max, obj) {
var x = document.getElementsByName("band");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
count += 1;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
</script>
Add[] in band i.e : document.getElementsByName("band[]") because javascript is not able to find that inputs .
Working Code :
var a, b = false;
function limit_checkbox(max, obj) {
//getting element by name
var x = document.getElementsByName("band[]");
var count = 0;
for (var i = 0; i < x.length; i++) {
if (x[i].checked) {
//incrementing
count++;
}
}
if (count > max) {
alert('You can select only ' + max + ' checkboxes.');
obj.checked = false;
}
}
<div class="form-group w-25" id="ch1">
<input type="checkbox" value="delta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Delta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="theta" name="band[]" onclick="limit_checkbox(2,this)">
<label>Theta</label>
</div>
<div class="form-group w-25">
<input type="checkbox" value="alpha" name="band[]" onclick="limit_checkbox(2,this)">
<label>Alpha</label>
</div>

add and delete divs created in JS

So I got this working almost perfectly but for some reason deleteInput() won't delete 2 div's in a row and I can not figure it out. The function still works but it won't delete. can someone explain why this is?
https://codepen.io/kScheid/pen/pLYXwE?editors=1010
HTML:
<div id="parent" class="first-div">
<label for="email">Email</label><input type="email" id="mail" name="usermail"> <div class="line-left shrinkM-underline"></div>
<div id="child" class="showE flex-it">
<div>
<input type="email"><div class="line-left shrinkM-underline"></div>
</div>
<span type="button" value="Remove Element" onClick="removeElement('parent','child');" class="remove"> <strong>Remove</strong></span>
</div>
<input onclick="addElement('parent', 'child');" class="input-button" type="button" value="+Add another email">
</div>
Javascript:
var counter = 1;
var limit = 5;
var newdiv = document.createElement('div');
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
newdiv = document.createElement('div');
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function deleteInput() {
for (var x = 0; x < counter; x++){
newdiv.removeChild(newdiv.childNodes[0]);
}
counter--;
}
Base format before JS
Added another Div w/JS
This may solve your problem if I understood what you are trying to do correctly. I've added an email class to your divs to remove the emails more easily.
var counter = 1;
var limit = 5;
function addInput(divName) {
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
} else {
var newdiv = document.createElement('div');
newdiv.className = "email"
newdiv.innerHTML = "Entry " + (counter + 1) + " <br><input type='text' name='myInputs[]'>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
function deleteInput(divName) {
var emails = document.getElementsByClassName("email");
if (emails.length) {
document.getElementById(divName).removeChild(emails[emails.length - 1]);
counter--;
}
}
<div id="parent" class="first-div">
<label for="email">Email</label><input type="email" id="mail" name="usermail">
<div class="line-left shrinkM-underline"></div>
<div id="child" class="showE flex-it">
<div>
<input type="email">
<div class="line-left shrinkM-underline"></div>
</div>
<span type="button" value="Remove Element" onClick="deleteInput('parent','child');" class="remove"> <strong>Remove</strong></span>
</div>
<input onclick="addInput('parent', 'child');" class="input-button" type="button" value="+Add another email">
</div>

adding option to a select in JavaScript not updating

the select option will not update till i add the innerHTML again.
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
i am stepping thorugh multiple input fields and gathering the values, these are then added to a new option element. when i appendChild to the selectaccount2 which is the select element, this does not insert the value. any ideas?
<!-- Text input-->
<div id="details" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label" for="accountNumber">Account Number</label>
<div class="col-md-4">
<input id="accountNumber" name="accountNumber" type="text" placeholder="your game account number" class="form-control input-md" required="" onchange="myFunction()">
</div>
</div>
</div>
<div id="DetailsFooter" style="display: none;">
<!-- Text input-->
<div class="form-group">
<label class="col-md-4 control-label">details</label>
<div class="col-md-4">
<select id="AccountToUse" name="AccountToUse" type="text" placeholder="" required="">
</select>
</div>
</div>
</div>
<fieldset id="DetailsView" class="DetailsView">
<h2>Details Applicant 1</h2>
<!-- Select Basic -->
<div class="form-group">
<label class="col-md-4 control-label" for="Accounts">How many accounts do you have?</label>
<div class="col-md-4">
<select id="Accounts" name="Accounts" class="form-control" onchange="amountchanged()">
<option value="0">Please Select an Amount</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
<div id="DetailsContainer">
</div>
</fieldset>
<script>
var select = document.getElementById("Accounts"),
container = document.getElementById("DetailsContainer");
var array = [];
var accountToUse;
var footer;
var num = 0;
function changeId(nodes, n) {
for (var i = 0; i < nodes.length; i = i + 1) {
if (nodes[i].childNodes) {
changeId(nodes[i].childNodes, n);
}
//if id value is 'accountNumber', change it
if (nodes[i].id && /^ch$|^accountNumber$/i.test(nodes[i].id)) {
nodes[i].id += String(n);
array.push(nodes[i]);
}
}
}
function amountchanged() {
var amount = select.value,
obj = document.getElementById("details").cloneNode(true),
children = obj.childNodes;
footer = document.getElementById("DetailsFooter");
container.innerHTML = "";
var count;
num += 1;
obj.id = obj.id + num;
if (num < 16) {
changeId(children, num);
}
document.body.appendChild(obj);
for (count = 1; count <= amount; count++) {
var heading = "<h3>" + count + " Details</h3>"
container.innerHTML += heading;
container.innerHTML += obj.innerHTML;
}
accountToUse = footer.getElementsByTagName("select")[0];
accountToUse.id = 'AccountToUse1';
container.innerHTML += footer.innerHTML;
}
function myFunction() {
for (index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var select22 = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = select22.value;
opt.innerHTML = select22.value;
select.value = "test";
selectaccount2.appendChild(opt);
}
}
</script>
Although I've seen people recommend adding an option the way you have there, so presumably it works on many if not most browsers, the most robust, reliable way I've ever found is the Option constructor and the add method:
selectaccount2.options.add(new Option(selectban.value));
If you just provide the value (the first argument), the text and value will be the same. If you give two arguments, the first is the text and the second is the value.
Live copy:
var array = [{
id: "one"
}, {
id: "two"
}, {
id: "three"
}];
function myFunction() {
for (var index = 0; index < array.length; ++index) {
var bAccount = array[index].id;
var selectban = document.getElementById(bAccount);
var selectaccount2 = document.getElementById("AccountToUse1");
var opt = document.createElement('option');
opt.value = selectban.value;
opt.innerHTML = selectban.value;
selectban.value = "test";
selectaccount2.appendChild(opt);
}
}
myFunction();
<select id="AccountToUse1" size="4"></select>
<input type="hidden" id="one" value="uno">
<input type="hidden" id="two" value="due">
<input type="hidden" id="three" value="tre">
Side note: You're falling prey to The Horror of Implicit Globals: Declare index.

Categories