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.
Related
Im trying to do simple calculation for the fee ,but its doesn't work ,there's no error in the code. Did I miss something in the script ?
<script type="text/javascript">
var bwm = 7.9;
var bswk = 14;
var bsbh = 15;
var wm = 2;
var swk = 11;
var sbh = 12;
var kilo, overkilo, f;
var s = document.getElementById('place');
var place = s.options[s.selectedIndex].value;
var k = document.getElementById('kilo').value;
var tot;
function quote() {
f = document.getElementById('theform');
f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
(k * swk) + bswk = tot;
} else if (place == 'sbh') {
(k * sbh) + bsbh = tot;
} else {
(k * wm) + bwm = tot;
}
document.getElementById('tot').value = 'RM ' + parseFloat;
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
The clear works fine ,but the calculate button won't work even i have input the KG and select a option to calculate .
You need to move the definition of the click handler outside of the change handler, unless the click handler would be defined only when an option changes and also it would be defined on every option change which is unnecessary.
Grab all the required values inside the click handler otherwise you would not have the updated values.
And you also need to set the selected index after resetting the form otherwise the change of option would not be visible.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
function quote(e) {
const selIndex = e.target.selectedIndex;
document.getElementById("theform").reset();
document.getElementById("place").selectedIndex = selIndex;
}
document.getElementById("calc").onclick = function () {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * swk + bswk;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
};
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote(event)">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
Instead of resetting the form you could also update the calculated value every time the option changes.
const
bwm = 7.9,
bswk = 14,
bsbh = 15,
wm = 2,
swk = 11,
sbh = 12;
document.getElementById("calc").onclick = handleClick;
function handleClick() {
const select = document.getElementById("place");
const place = select.options[select.selectedIndex].value;
const k = document.getElementById("kilo").value;
if (!k) {
return;
}
let tot;
if (place === "swk") {
tot = k * 10 + 10;
} else if (place === "sbh") {
tot = k * sbh + bsbh;
} else {
tot = k * wm + bwm;
}
document.getElementById("tot").value = "RM " + tot;
}
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="handleClick()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="button" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
I Removed the left-hand side for assignment and set the value.
You defined the var for all instead of that you can use const.
Also form reset not required.
Here is solution of your code
<html>
<script type="text/javascript">
const bwm = 7.9;
const bswk = 14;
const bsbh = 15;
const wm = 2;
const swk = 11;
const sbh = 12;
let kilo, overkilo, f;
var tot;
function quote() {
const s = document.getElementById('place');
const place = s.options[s.selectedIndex].value;
const k = document.getElementById('kilo').value;
f = document.getElementById('theform');
// f.reset();
document.getElementById('calc').onclick = function() {
if (place == 'swk') {
tot = (k * swk) + bswk;
} else if (place == 'sbh') {
tot = (k * sbh) + bsbh;
} else {
tot = (k * wm) + bwm;
}
document.getElementById('tot').value = 'RM ' + parseFloat(tot);
}
}
</script>
<form id="theform" action="#">
<div>
<label for="place">Choose Destination :</label>
<select id="place" onChange="quote()">
<option value="swk">Sarawak</option>
<option value="sbh">Sabah</option>
<option value="wm">WestMalaysia</option>
</select>
</div>
<div>
<label for="kilo">Amount of KG :</label>
<input id="kilo" type="text">
</div>
<div>
<label>Total :</label>
<input id="tot" type="text" readonly="readonly">
</div>
<div>
<label></label>
<input id="calc" type="submit" value="calculate">
<input id="r" type="reset" value="clear">
</div>
</form>
</html>
I have created a form which can be dynamically changed using the buttons included. These buttons allow for more input fields to be added/removed. The issue is that the input fields created are not posting any data/ Values in those fields not being added to the $POST array on the submit of the form.
The main functions below resposible for adding and removing rows is RemoveRows() and addRows()
What should happen is that on submit all values in the form should be "posted" then I can access all of those fields via $_POST["nameOfField"].
The way I have currently approached this is to create an input fields with the relevant id's and names then append that field to where the "hard coded" fields exists.
From my initial debugging none of the fields that have been added via javascript are in $Post which I have checked via var_dump($_REQUEST);
I have also seen that the nodes that are added are not elements of the form tag even though the nodes are added between the opening and closing tag. This can be seen in the doBeforeSubmit() Function where we can see all elements that are children of the and this never changes as rows are added/removed.
function showPlatforms() {
let nacellesOptions = ["Option1", "option2", "Option3"];
let milOptions = ["Option1", "option2", "Option3"]
let highOptions = ["Option1", "option2", "Option3"]
let entry = document.getElementById("vs")
let platfom = document.getElementById("platform")
if (platform.hasChildNodes()) {
var lastChild = platfom.lastElementChild
while (lastChild) {
platfom.removeChild(lastChild)
lastChild = platform.lastElementChild
}
}
if (entry.value == "Nacelles") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = nacellesOptions[i]
option.innerHTML = nacellesOptions[i]
platform.appendChild(option)
}
} else if (entry.value == "Military") {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = milOptions[i]
option.innerHTML = milOptions[i]
platform.appendChild(option)
}
} else {
for (var i = 0; i < 2; i++) {
var option = document.createElement("option");
option.value = highOptions[i]
option.innerHTML = highOptions[i]
platform.appendChild(option)
}
}
}
function formOptions() {
let entry = document.getElementById("type")
if (entry.value == "Engineering MAM") {
document.getElementById("WBS").disabled = false
document.getElementById("Desc").disabled = false
document.getElementById("ProName").disabled = false
} else {
document.getElementById("WBS").disabled = true
document.getElementById("Desc").disabled = true
document.getElementById("ProName").disabled = true
}
}
function formoptions2() {
let entry2 = document.getElementById("organisation")
if (entry2.value == "Aftermarket") {
document.getElementById("COT").disabled = false
document.getElementById("COC").disabled = false
} else {
document.getElementById("COT").disabled = true
document.getElementById("COC").disabled = true
}
}
count = document.getElementById("partNum").childElementCount
function addRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(addRow, count)
count = document.getElementById("partNum").childElementCount
//doBeforeSubmit()
}
function doBeforeSubmit() {
var es = document.getElementById("form").elements;
var l = es.length;
var msgs = [];
for (var idx = 0; idx < l; idx++) {
var e = es[idx];
msgs.push('name=' + e.name + ', type=' + e.type + ', value=' + e.value);
}
alert(msgs.join('\n'));
return false;
}
function addRow(id) {
let col = document.getElementById(id)
var box = document.createElement("INPUT")
box.setAttribute("type", "text")
box.setAttribute("id", id + count)
box.setAttribute("name", id + count)
box.setAttribute("class", "form-control")
col.appendChild(box)
}
function RemoveRows() {
rowNames = ["partNum", "partDesc", "leadTime", "quantity", "dateReq", "unitCost", "unitExtention", "unitSaleValue", "estSalesValue"]
rowNames.forEach(removeBoxes)
count = document.getElementById("partNum").childElementCount
}
function removeBoxes(item) {
let box = document.getElementById(item)
let last = box.lastChild
box.removeChild(last)
}
function checkData() {
// if all stuff is correct do this:
document.getElementById("submit").disabled = false
// else dont activate the submit button.
}
<form method="post" id="form" action="SubmitMAM.php">
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNo" class="col-2">
<h3>Part Number:</h3>
</div>
<div class="col-2">
<h3>Part Description:</h3>
</div>
<div class="col-1">
<h3>Lead Time:</h3>
</div>
<div class="col-1">
<h3>Quantity:</h3>
</div>
<div class="col-1">
<h3>Date Required:</h3>
</div>
<div class="col-1">
<h3>Unit Cost:</h3>
</div>
<div class="col-2">
<h3>Unit Cost Extension:</h3>
</div>
<div class="col-1">
<h3>Unit Sale Value:</h3>
</div>
<div class="col-1">
<h3>Est Sales Value:</h3>
</div>
</div>
<div class="row" id="productRow" style="width:95%; margin:auto">
<div id="partNum" class="col-2">
<input type="text" id="partNum0" class="form-control" name="partNum0">
</div>
<div id="partDesc" class="col-2">
<input type="text" id="partDesc0" class="form-control" name="partDesc0">
</div>
<div id="leadTime" class="col-1">
<input type="text" id="leadTime0" class="form-control" name="leadTime0">
</div>
<div id="quantity" class="col-1">
<input type="text" id="quanitity0" class="form-control" name="quantity0">
</div>
<div id="dateReq" class="col-1">
<input type="text" id="dateReq0" class="form-control" name="dateReq0">
</div>
<div id="unitCost" class="col-1">
<input type="text" id="unitCost0" class="form-control" name="unitCost0">
</div>
<div id="unitExtention" class="col-2">
<input type="text" id="unitExtention0" class="form-control" name="unitExtention0">
</div>
<div id="unitSaleValue" class="col-1">
<input type="text" id="unitSaleValue0" class="form-control" name="unitSaleValue0">
</div>
<div id="estSalesValue" class="col-1">
<input type="text" id="estSalesValue0" class="form-control" name="estSalesValue0">
</div>
<button onclick="addRows()" class="btn btn-primary" type="button">Add a Product</button>
<button onclick="RemoveRows()" class="btn btn-primary" type="button">Remove Row</button>
<button onclick="checkData()" class="btn btn-primary" type="button">Check Data</button>
<br>
<button type="submit" name="submit" id="submit" class="btn btn-primary" disabled>Submit</button>
</form>
PHP:
<?php
var_dump($_REQUEST)
?>
UPDATE:
The code has been changed to use a php array by adding square brackets into the name which produces the following html:
<input type="text" id="partNum0" class="form-control" name="partNum[]">
<input type="text" id="partNum1" name="partNum[]" class="form-control">
<input type="text" id="partNum2" name="partNum[]" class="form-control">
You just need to use the name property of the input and add [] at the end, as GrumpyCrouton said. PHP parse it as an array, and you can access it as:
$partNum = $_POST["partNum"];
FIXED: It turns out the above code did not have any issues with the logic or the way it should work, in the source code in visual studio the indentation of some of the Divs was off causing the browser to have issues in rendering the form correctly hence why the added boxes were not included in the form and their values not POSTED.
As a heads up to anyone with maybe a similar issue, it pays to have your code neat.
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
I was wondering how can I delete a specific sessionStorage value from the key worker as well as decrement the key limit value by 1 without affecting the other sessionStorage values every time a specific key worker is deleted?
Here is my Jsfiddle https://jsfiddle.net/d7e92k5d/2/
HTML
<ul>
<li>
<div class="worker-container-last">
<label class="worker-label"><input type="text" class="first-name" /></label>
</div>
<div class="worker-container-last">
<label class="worker-label"><input type="text" class="last-name" /></label>
</div>
<div class="worker-container-last">
<label class="worker-label">
<select name="title[]" class="title">
<option value="Select a Title" selected="selected">Select a Title</option>
<option value="Boss">Boss</option>
<option value="Worker">Worker</option>
<option value="Manager">Manager</option>
</select>
</label>
</div>
<div class="add-more"></div>
<div><a class="worker" title="" href="">Add Another Worker</a></div>
</li>
</ul>
JQuery
var worker_record = [];
$(document).ready(function(){
new_worker();
$('.worker').on('click', function(e){
e.preventDefault();
e.stopPropagation();
if(sessionStorage.getItem("limit") === null){
sessionStorage.setItem('limit', 0);
}
if(sessionStorage.getItem('limit') <= 2){
var first_name = $('.first-name').val();
var last_name = $('.last-name').val();
var title = $('.title:first').val();
var tblObj = {first_name: first_name, last_name: last_name, title: title};
worker_record.push(tblObj);
sessionStorage.worker = JSON.stringify(worker_record);
new_worker();
var count = sessionStorage.getItem('limit');
count++;
sessionStorage.setItem('limit', count);
}
});
function new_worker(){
var max_fields = 3;
var x = 0;
if(!(typeof sessionStorage.worker === 'undefined' || sessionStorage.worker.length<1)){
worker_record = JSON.parse(sessionStorage.worker);
}
$('.add-more').empty();
for(var i=0; i<worker_record.length; i++){
if(x < max_fields){
x++;
var first_name = worker_record[i].first_name;
var last_name = worker_record[i].last_name;
var title = worker_record[i].title;
var worker = '<div class="worker-container"><div class="delete-worker"><a title="" href="#">Delete</a></div><div class="update-worker"><a title="" href="#">Update</a></div><div class="worker-box"><label class="another-worker"><input type="text" name="workers_first_name[]" class="first-name" value="' + first_name + '" /></label></div><div class="worker-box"><label class="another-worker"><input type="text" name="workers_last_name[]" class="last-name" value="' + last_name + '" /></label></div><div class="worker-box-last"><label class="another-worker"><select name="workers_title[]" class="title workers-title-options"><option value="Select a Title" selected="selected">Select a Title</option><option value="Boss">Boss</option><option value="Worker">Worker</option><option value="Manager">Manager</option></select></label></div></div>';
$('.add-more').append(worker);
$('.title:eq('+$('.workers-title-options').length+')').val(title);
}
}
$('.first-name:first').val('');
$('.last-name:first').val('');
$('.title:first').val('Select a Title');
}
$('.add-more').on('click', '.delete-worker', function(e){
e.preventDefault();
e.stopPropagation();
$(this).parent('div').remove();
worker_record = JSON.parse(sessionStorage.worker);
worker_record.splice(worker_record.length -1, 1);
sessionStorage.worker = JSON.stringify(worker_record);
});
});
I want to create a program where I can copy a div over and over again, which contains two drop down buttons and to input forms. Copying a div with its elements is already solved, the problem is that this div contains two drop down buttons which are connected by a function: when one button option is selected, the other one shows respective choices. So copying a div with these two drop down buttons work, but they aren't connected anymore. How do I declare that for every new div the function ChangeCarList will work with those two only ir particular div? Sorry for a messy formulation, but here's the code:
<!DOCTYPE html>
<html>
<body>
<div id="Item1">
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<input type="text" value="number1">
<input type="text" value="number2">
<TD width="200" rowspan="3" valign="top"></STRONG><span style="color: #ff0000">*</span>
<input type="button" name="" id="" value="+" onclick="addItem('Item1');" style="20;" class="FieldBlack"></input>
<input type="button" name="" id="" value="-" onclick="parentNode.remove()" class="FieldBlack"></input>
</TD>
</div>
<script>
function addItem(div)
{
var ediv=document.getElementById("Item1");
var temp=ediv.innerHTML;
var newdiv = document.createElement('div');
var divIdName=div+1;//i hav taken 1 for sample for adding id to the div
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML =temp;
ediv.parentNode.insertBefore(newdiv, ediv.nextSibling);
}
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = document.getElementById("car");
var modelList = document.getElementById("carmodel");
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>
Here you go
function ChangeCarList() {
var carList = event.target;
console.log(carList);
var modelList = carList.parentNode.querySelectorAll('select')[1];
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
RE-EDIT FUll VerSIOn
<!DOCTYPE html>
<html>
<body>
<div id="cars">
<div id="Item1">
<select id="car" onchange="ChangeCarList()">
<option value="">-- Car --</option>
<option value="VO">Volvo</option>
<option value="VW">Volkswagen</option>
<option value="BMW">BMW</option>
</select>
<select id="carmodel"></select>
<input type="text" value="number1">
<input type="text" value="number2">
<TD width="200" rowspan="3" valign="top"></STRONG><span style="color: #ff0000">*</span>
<input type="button" name="" id="" value="+" onclick="addItem('Item1');" style="20;" class="FieldBlack"></input>
<input type="button" name="" id="" value="-" onclick="parentNode.remove()" class="FieldBlack"></input>
</TD>
</div>
</div>
<script>
function addItem(div)
{
var ediv=document.getElementById("Item1");
var temp=ediv.innerHTML;
var newdiv = document.createElement('div');
var divIdName=div+1;//i hav taken 1 for sample for adding id to the div
newdiv.setAttribute('id',divIdName);
newdiv.innerHTML =temp;
document.getElementById('cars').appendChild(newdiv);
}
var carsAndModels = {};
carsAndModels['VO'] = ['V70', 'XC60', 'XC90'];
carsAndModels['VW'] = ['Golf', 'Polo', 'Scirocco', 'Touareg'];
carsAndModels['BMW'] = ['M6', 'X5', 'Z3'];
function ChangeCarList() {
var carList = event.target;
console.log(carList);
var modelList = carList.parentNode.querySelectorAll('select')[1];
var selCar = carList.options[carList.selectedIndex].value;
while (modelList.options.length) {
modelList.remove(0);
}
var cars = carsAndModels[selCar];
if (cars) {
var i;
for (i = 0; i < cars.length; i++) {
var car = new Option(cars[i], i);
modelList.options.add(car);
}
}
}
</script>
</body>
</html>