I am trying dynamically increase the number of selects my form has on a website. I use javascript to do so.
JS code:
var div = document.getElementById("graph-form");
var para = document.createElement('span');
para.innerHTML = "Test Type";
var form = document.getElementById("form-id");
var selectList = document.createElement("select");
selectList.setAttribute("name","Test");
for(var i = 0; i < test_form_values.length; i++){
var option = document.createElement("option");
option.value = test_form_values[i];
option.text = test_form_text[i];
selectList.appendChild(option);
}
form.appendChild(para);
form.appendChild(selectList);
var para = document.createElement('span');
para.innerHTML = "Parameter";
var selectList = document.createElement("select");
selectList.setAttribute("name","Parameter");
for(var i = 0; i < param_form_values.length; i++){
var option = document.createElement("option");
option.value = param_form_values[i];
option.text = param_form_text[i];
selectList.appendChild(option);
}
form.appendChild(para);
form.appendChild(selectList);
Html code:
<form action="/analytics" method = "post"></form>
<div id = "form-id">
<span>Test Type </span>
<select name="Test">
<option value="Aop2DContact">AOP 2D Contact</option>
<option value="Aop2DMag">AOP 2D Magnification</option>
</select>
<span>Parameter </span>
<select name="Parameter">
<option value="MTF1">MTF at 2 lp/mm parallel</option>
<option value="MTF2">MTF at 4 lp/mm parallel</option>
</select>
</div>
<div class="buttons">
<input type="submit">
</div>
</form>
After appending:
After I append the newly created elements, it not only doesn't append inside the element but takes the div I had placed inside the element and moved it outside. I feel like there is probably an obvious answer as to why my HTML is getting restructured but I am not sure what that is.
Like Turnip commented, you are ending your form right after you open it.
Also, your JS is looking to append to the element with the id "form-id" and your form does not have that id, your inner div does.
Related
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
const container = document.getElementById("stringcontainer");
var select = createSelect(1);
select.addEventListener('change', hello);
container.appendChild(select);
function add(){
var select1 = createSelect(2);
select1.addEventListener('change', hello);
container.appendChild(select1);
}
function createSelect(num){
//Create array of options to be added
var array = ["Option 1","Option 2","Option 3"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "asp"+num;
//selectList.className = "browser-default";
selectList.required = true;
selectList.innerHTML += "<option disabled selected>Choose Option</option>"
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].split(" ").join("").toLowerCase();
option.text = array[i];
selectList.appendChild(option);
}
return selectList;
}
function hello(){
console.log("Added EventListener");
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/css/materialize.min.css">
<div class="row">
<div id="stringcontainer"/>
</div><!-- CLOSE ROW -->
<div class="row">
<div class="input-field col s3">
<button id="astring" class="waves-effect waves-light btn-small"
onclick="add()">Add</button>
</div>
</div><!-- CLOSE ROW -->
<script src="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/js/materialize.min.js"></script>
Called from JS as a function:
Called from a button with the same function:
The result is an invisible unstyled select when you press the button.
I'm using Materialize CSS. The eventListener is also not working properly when adding from the button also. It works for a console log but anything more complex like getSelectedValues(), it fails
I expected the Select to render the same way as the first image. Can anyone explain why this happening and offer a solution?
The problem is, you apply the css only once in the beginning by using
document.addEventListener('DOMContentLoaded', function() {
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
});
You have to do the same, each time you add a new select. So, the following should work the way you want it to.
document.addEventListener('DOMContentLoaded', function() {
applyCSS();
});
const container = document.getElementById("stringcontainer");
var select = createSelect(1);
select.addEventListener('change', hello);
container.appendChild(select);
function add(){
var select1 = createSelect(2);
select1.addEventListener('change', hello);
container.appendChild(select1);
applyCSS();
}
function createSelect(num){
//Create array of options to be added
var array = ["Option 1","Option 2","Option 3"];
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "asp"+num;
//selectList.className = "browser-default";
selectList.required = true;
selectList.innerHTML += "<option disabled selected>Choose Option</option>"
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.value = array[i].split(" ").join("").toLowerCase();
option.text = array[i];
selectList.appendChild(option);
}
return selectList;
}
function hello(){
console.log("Added EventListener");
}
function applyCSS(){
var elems = document.querySelectorAll('select');
var instances = M.FormSelect.init(elems, {});
}
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/css/materialize.min.css">
<div class="row">
<div id="stringcontainer"/>
</div><!-- CLOSE ROW -->
<div class="row">
<div class="input-field col s3">
<button id="astring" class="waves-effect waves-light btn-small"
onclick="add()">Add</button>
</div>
</div><!-- CLOSE ROW -->
<script src="https://cdn.jsdelivr.net/npm/#materializecss/materialize#1.1.0/dist/js/materialize.min.js"></script>
I moved the code, which applies the CSS into applyCSS and then call it once in the DOMContentLoaded event listener and also each time the add function is called.
I'm trying to create a list of checkboxes when a certain element is selected from the dropdown list. However, in the following code I am getting only the last element in the checkbox list. That is, at the output, there aren't 3 checkboxes (length of my array) but there is only one - only with the last element in the array.
What am I doing wrong?
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<script>
function chooseTable(db) {
if(db=="hr.employee"){
var div = document.getElementById("table");
var ids = ["id","name", "write_uid"];
var main = document.getElementById('main1');
var parentElement = document.getElementById('ids');
for(var count in ids)
{
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
parentElement.innerHTML = ids[count];
newCheckBox.value = ids[count];
parentElement.appendChild(newCheckBox);
}
}
}
</script>
<center>
<bold>
<h2>
Make Query
</h2>
</bold>
<div id="main1">
<div>
Choose database:<br/>
<select id="table" name="table" onchange="chooseTable(this.value)">
<option name="choice" value=""></option>
<option name="choice1" value="hr.employee">Employees</option>
<option name="choice2" value="account.account">Accounts</option>
</select>
</div>
<div id="ids">
</div>
</div>
</center>
</body>
</html>
the problem is the parentElement.innerHTML = ids[count]; code. It clean all the previous html content. And to add label to the checkbox it's better use label tag. Try this:
for(var count in ids)
{
var newCheckBox = document.createElement('input');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
newCheckBox.value = ids[count];
parentElement.appendChild(newCheckBox);
var newLabel = document.createElement('label');
newLabel.innerHTML = ids[count];
parentElement.appendChild(newLabel);
}
because innerHTML method will clean its own inside and rewrite new element.
how about try this?
for(var count in ids)
{
var newCheckBox = document.createElement('input');
var newSpan = document.createElement('span');
newCheckBox.type = 'checkbox';
newCheckBox.id = 'id' + count; // need unique Ids!
newSpan.innerHTML = ids[count];
newCheckBox.value = ids[count];
parentElement.appendChild(newSpan);
parentElement.appendChild(newCheckBox);
}
I have a dynamic form with a select dropdown, and I want to know what select was changed, however any time that I add a new form and try to change any select the alert is the same: "origen1"
Here is my js code:
<SCRIPT language="javascript">
function addRow(divId) {
count = 0;
count++;
var etiquetas = new Array();
var origenes = new Array();
var parentDiv = document.getElementById(divId);
// create a div dynamically
var eleDiv = document.createElement("div");
eleDiv.setAttribute("name", "olddiv");
eleDiv.setAttribute("id", "olddiv");
// create a label dynamically
var etiqueta = document.createElement("input");
etiqueta.setAttribute("name", 'etiqueta' + count);
etiqueta.setAttribute("value", "etiqueta");
etiqueta.setAttribute('disabled', true);
etiquetas.push(etiqueta);
//create a select dynamically
var myarray=new Array(3)
myarray[0] = "Opt1"
myarray[1] = "Opt2"
myarray[2] = "Opt3"
var origen = document.createElement("select");
origen.setAttribute("name", 'origen' + count);
for (i=0; i<3; i++)
{
opt = document.createElement('option');
opt.value = i;
opt.innerHTML = myarray[i];
origen.appendChild(opt);
}
origen.onchange = function(){testselect(this);};
origenes.push(origen);
// create a delete button dynamically
var eleBtn = document.createElement("input");
eleBtn.setAttribute("type", "button");
eleBtn.setAttribute("value", "delete");
eleBtn.setAttribute("name", "button");
eleBtn.setAttribute("id", "button");
eleBtn.setAttribute("onclick", "deleteRow('button')");
// append new div to parent div
parentDiv.appendChild(eleDiv);
// append textbox & button to new div
eleDiv.appendChild(etiqueta);
eleDiv.appendChild(origen);
eleDiv.appendChild(eleBtn);
}
function testselect(seleccion)
{
alert(seleccion.name);
}
function deleteRow(tableID) {
var div = document.getElementById('olddiv');
if (div) {
div.parentNode.removeChild(div);
}
}
</SCRIPT>
And the html:
<form name="objForm" action="test1.php">
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<div id="dataTable" width="350px">
</div>
<input type="submit" value="Submit"/>
</form>
Try inspecting the drop down using firebug. With that you might be able to get the name and ID of the selected drop down but remember the selected drop down has to be selected using firebug in order to see the ID or name used with it.
Since this is JS and the drop down is not selected properly you might not see the name or id used.
So make sure to it is properly selected
I need to add a dropdown list to a webpage.
generally the HTML code is like this;
<select id="au_1_sel" name="au_1_sel" class="searchw8">
<option value="AU" selected="">method1</option>
<option value="FI">method2</option>
</select>
How can I use JavaScript to create a element like above.
after I create this drop down list. I need to add it after a button.
var button = document.getElementById("button1");
and I already get the button element.
Also, when the button is clicked, I want to know which option the people have choose in the dropdown list. How can I do that using JavaScript.
I try this
var select = document.createElement("select");
select.id = "wayToCalculate";
//select.name="au_1_sel";
//select.class=class="searchw8";
var option1 = document.createElement("option");
option1.value="1";
option1.selected="";
option1.innerHTML= "1";
var option2 = document.createElement("option");
option2.value="2";
option2.innerHTML= "2";
var option3 = document.createElement("option");
option3.value="3";
option3.innerHTML= "3";
select.addChild(option1);
select.addChild(option2);
select.addChild(option3);
$(select).insertAfter(button);
but when it comes to this.
select.addChild(option1);
chrome browser give me a error.
Uncaught TypeError: undefined is not a function
It seems that addChild does not work here.
Example
HTML:
<div id="container">
<button id="button1">button1</button>
</div>
JavaScript
var div = document.querySelector("#container"),
frag = document.createDocumentFragment(),
select = document.createElement("select");
select.options.add( new Option("Method1","AU", true, true) );
select.options.add( new Option("Method2","FI") );
frag.appendChild(select);
div.appendChild(frag);
var select = document.createElement("select");
select.id = "au_1_sel";
select.name="au_1_sel";
select.class=class="searchw8";
var option1 = document.createElement("option");
option.value="AU";
option.selected="";
option.innerHTML= "method1";
var option2 = document.createElement("option");
option.value="FI";
option.innerHTML= "method2";
select.addChild(option1);
select.addChild(option2);
document.addChild(select);
var button = document.getElementById("button1");
button.onClick=function(){alert(select.options[select.selectedIndex].value);}
This is the HTML I'm trying to create:
<td>
Tiana is
<select name="U4">...</select>
keen to go to the
<select name="J4">...</select>
market.
</td>
As you can see, there is a <td> element which contains a prose sentence with select boxes in the midst of it.
It's easy to do with $('#id').html(...);. What I want to do is build it using createElement. How do you create the select boxes in the middle of the other text? The following code is a start :)
var doc = document,
fr = doc.createDocumentFragment(),
td = doc.createElement("td"),
sel1 = doc.createElement("select"),
sel2 = doc.createElement("select");
td.innerHTML = "Tiana is keen to go to the market";
sel1.name = "U4";
sel2.name = "J4";
fr.appendChild(td);
td.appendChild(sel1); // But these are not in the middle of the sentence
td.appendChild(sel2);
BTW: I recognise, too, that I'll have to create the select options.
Thanks.
There is also a function called createTextNode() (MDN docu) for creating simple text as content. So one solution would be to split your text accordingly, transform it to textnodes and then append it as well:
var doc = document,
fr = doc.createDocumentFragment(),
td = doc.createElement("td"),
sel1 = doc.createElement("select"),
sel2 = doc.createElement("select"),
text1 = doc.createTextNode( 'Tiana is ' ),
text2 = doc.createTextNode( ' keen to go to the ' ),
text3 = doc.createTextNode( 'market' );
sel1.name = "U4";
sel2.name = "J4";
fr.appendChild(td);
td.appendChild( text1 );
td.appendChild(sel1);
td.appendChild( text2 );
td.appendChild(sel2);
td.appendChild( text3 );
Here you can find an example fiddle: link.
I think you'll need to have this:
<td>
<span>Tiana is</span>
<select name="U4">...</select>
<span>keen to go to the</span>
<select name="J4">...</select>
<span>market.</span>
</td>
or do this:
td.innerHTML = 'Tiana is <select id="U4" name="U4" /> keen to go to the <select id="J4" name="J4" /> market';
var uOpt1 = document.createElement('option');
//Set option properties
td.getElementById('U4').appendChild(uOpt1); //etc
How about this? I adapted the example from mdn createElement. Fiddle.
<div id='org_div1'> The text above has been created dynamically.</div>
var my_div = null;
var newDiv = null;
var newSelect = null;
var newDiv2 = null;
function addElement()
{
// create a new div element
// and give it some content
newDiv = document.createElement("div");
newContent = document.createTextNode("Hi there and greetings!");
newSelect = document.createElement("select");
newSelect.innerHTML='<option value="value1">Value 1</option><option value="value2" selected>Value 2</option><option value="value3">Value 3</option>';
newDiv.appendChild(newContent); //add the text node to the newly created div.
newDiv.appendChild(newSelect)
newDiv2 = document.createElement("span");
newDiv2.appendChild(document.createTextNode("Foo"));
newDiv.appendChild(newDiv2)
// add the newly created element and it's content into the DOM
my_div = document.getElementById("org_div1");
document.body.insertBefore(newDiv, my_div);
}
addElement()