Creating an object every time I call a function - javascript

Codepen with my working application
I have the following:
<button onClick="createBox()" id="box">Create Box</button>
and this is my function:
function createBox()
{
var obj = {
"1": "",
"12": "",
"123": "",
"1234": "",
"12345": "",
"123456": ""
};
console.log(obj)
document.getElementById("box").onclick = function () {
var div = document.createElement('div');
div.className = 'new-box';
document.getElementsByTagName('body')[0].appendChild(div);
}
}
I want to create a new box with a new object every time I click the button. After that, I would like to click one box and fill that object box with my select list:
<select id="asdf" class="selectVal">
<option value="1">asdf</option>
<option value="2">asdf1</option>
<option value="3">asdf2</option>
</select>
<select id="asdf" class="selectVal">
<option value="1">asdf1</option>
<option value="2">asdf2</option>
<option value="3">asdf3</option>
<option value="4">asdf4</option>
</select>
<select id="asdf" class="selectVal">
<option value="1">asdf1</option>
<option value="2">asdf2</option>
<option value="3>asdf3</option>
<option value="4">asdf4</option>
<option value="asdf5>asdf5</option>
<option
I have the following code for filling the object:
function getSelectedItems() {
var elements = document.querySelectorAll('.selectVal, input');
var results = {};
for (var i = 0; i < elements.length; i++) {
var element = elements[i];
var strSel = '';
if (element.tagName == 'SELECT'){
strSel = element.options[element.selectedIndex].text;
}
else if (element.tagName == 'INPUT'){
strSel = element.value;
}
results[element.id] = strSel;
console.log(results)
}
strSel = JSON.stringify(results, null, 4);
var blob = new Blob([strSel], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "file.json";
a.href = url;
a.textContent = "Download JSON";
console.log(strSel);
document.getElementById('json').innerHTML = strSel;
document.getElementById('download').appendChild(a);
So I need to adapt my code to create independent boxes with independent objects that I can fill through my selects and inputs to download the JSON.

Related

How to add value attribute to option element from array in javascript?

I have two drop down lists, second is dependent on the first one. What I don´t know is how add different value to node.value (value of option element).
EDIT: At this moment I have same value in textContent and in value of html option element but I need to add different value from textContent.
e.g. Inhabitants
var moduly = [];
moduly['1'] = ["Inhabitants", "Married"];
moduly['2'] = ["German", "French", "English"];
moduly['3'] = ["Houses", "Estates"];
moduly['4'] = ["Surface area", "Meadow area"];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose module";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element;
node.textContent = element;
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
</form>
You are using a var that isn't defined, which throws an error:
var elementvalue = mvalue[this.value.toString().toLowerCase()];
Because the var elementvalue is also not used, you can comment that line out or delete it. Furthermore you try to clone a select element with the name itemSelect which doesn't exist in this example code. The following line is missing:
<select id="itemSelect" name="itemSelect"></select>
Fix both errors and yout code should work as expected.
Working example: (i added a disabled option like in the second select so that you can select the first option "Demographics" and renamed the second disabled option from "Choose modul" to "Choose item" so that you can differentiate between both)
var moduly = [];
moduly['1'] = ["Inhabitants", "Married"];
moduly['2'] = ["German", "French", "English"];
moduly['3'] = ["Houses", "Estates"];
moduly['4'] = ["Surface area", "Meadow area"];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
//var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose item";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element;
node.textContent = element;
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="0" disabled selected>Choose module</option>
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
<select id="itemSelect" name="itemSelect"></select>
</form>
If you want different value/content pairs you can nest your moduly array one step deeper. Change the array for example from:
moduly['3'] = ["Houses", "Estates"];
to
moduly['3'] = [["10", "Houses"], ["11", "Estates"]];
Then you just need to output the data with array notation:
node.value = element[0];
node.textContent = element[1];
var moduly = [];
moduly['1'] = [["5", "Inhabitants"], ["6", "Married"]];
moduly['2'] = [["7", "German"], ["8", "French"], ["9", "English"]];
moduly['3'] = [["10", "Houses"], ["11", "Estates"]];
moduly['4'] = [["12", "Surface area"], ["13", "Meadow area"]];
document.querySelector("select[name='modulSelect']").addEventListener("change", function() {
var element = moduly[this.value.toString().toLowerCase()];
//var elementvalue = mvalue[this.value.toString().toLowerCase()];
if (element) {
var select = document.querySelector("select[name='itemSelect']").cloneNode();
var node = document.createElement("option");
node.value = 0;
node.setAttribute("disabled", true);
node.setAttribute("selected", true);
node.textContent = "Choose item";
select.appendChild(node);
moduly[this.value.toString().toLowerCase()].forEach(function(element) {
var node = document.createElement("option");
node.value = element[0];
node.textContent = element[1];
select.appendChild(node);
});
document.querySelector("select[name='itemSelect']").parentElement.replaceChild(select, document.querySelector("select[name='itemSelect']"));
}
}, false);
<form>
<select id="modulSelect" name="modulSelect">
<option value="0" disabled selected>Choose module</option>
<option value="1">Demographics</option>
<option value="2">Nation</option>
<option value="3">Property</option>
<option value="4">Area</option>
</select>
<select id="itemSelect" name="itemSelect"></select>
</form>

Hide/Show next Select-statement when an Option is Picked in my first Select-statement

I'm currently trying to hide the subcategory-select-statement for aslong as there is no maincategory picked in my first select-statement. The same counts for the select-type-statement within the subcategory. The method for a cascading dropdown I use is the same you can find on w3schools, otherwise the code is down below.
Do you know how i can hide the subcategory/type while the select-hierarchy above isn't selected?
For example:
Choose Maincategory(default is "Select Category)", when I change "Select Category" to "MainCategory1" then the select statement of the subcategory appears. Then when the Subcategory option is picked, the typecategory select statement appears.
I hope it is clear what I want to do. Furthermore please excuse my bad use of english. English is not my mother tongue.
var maincatObject = {
"MainCategory1": {
"Subcategory 1.1": ["Type 1.1.1", "Type 1.1.2"],
"Subcategory 1.2": ["Type 1.2.1", "Type 1.2.2"],
"Subcategory 1.3": ["Type 1.3.1", "Type 1.3.2"],
"Subcategory 1.4": ["Type 1.4.1", "Type 1.4.2"]
},
"MainCategory2": {
"Subcategory 2.1": ["Type 2.1.1", "Type 2.1.2"],
"Subcategory 2.2": ["Type 2.2.1", "Type 2.2.2"],
"Subcategory 2.3": ["Type 2.3.1", "Type 2.3.2"],
"Subcategory 2.4": ["Type 2.4.1", "Type 2.4.2"]
}
}
window.onload = function() {
var maincatSel = document.getElementById("maincat");
var subcatSel = document.getElementById("subcat");
var typedevSel = document.getElementById("typedev");
for (var x in maincatObject) {
maincatSel.options[maincatSel.options.length] = new Option(x, x);
}
maincatSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
typedevSel.length = 1;
subcatSel.length = 1;
//display correct values
for (var y in maincatObject[this.value]) {
subcatSel.options[subcatSel.options.length] = new Option(y, y);
}
}
subcatSel.onchange = function() {
//empty Chapters dropdown
typedevSel.length = 1;
//display correct values
var z = maincatObject[maincatSel.value][this.value];
for (var i = 0; i < z.length; i++) {
typedevSel.options[typedevSel.options.length] = new Option(z[i], z[i]);
}
}
}
<select name="maincat" id="maincat">
<option value="" selected="selected">Select Category</option>
</select>
<br><br> Sub-Category:
<select name="subcat" id="subcat">
<option value="" selected="selected">Please select sub-category first</option>
</select>
<br><br> Type/Device:
<select name="typedev" id="typedev">
<option value="" selected="selected">Please select type or device</option>
</select>
<br><br>
Solution:
I managed to do it, for those of you who wonder how I did it... here's the modified JS code:
window.onload = function() {
var maincatSel = document.getElementById("maincat");
var subcatSel = document.getElementById("subcat");
var typedevSel = document.getElementById("typedev");
for (var x in maincatObject) {
maincatSel.options[maincatSel.options.length] = new Option(x, x);
subcatSel.style.display = 'none';
typedevSel.style.display = 'none';
}
maincatSel.onchange = function() {
//empty Chapters- and Topics- dropdowns
subcatSel.style.display = 'block';
typedevSel.style.display = 'none';
subcatSel.length = 1;
typedevSel.length = 1;
//display correct values
for (var y in maincatObject[this.value]) {
subcatSel.options[subcatSel.options.length] = new Option(y, y);
}
}
subcatSel.onchange = function() {
//empty Chapters dropdown
typedevSel.style.display = 'block';
typedevSel.length = 1;
//display correct values
var z = maincatObject[maincatSel.value][this.value];
for (var i = 0; i < z.length; i++) {
typedevSel.options[typedevSel.options.length] = new Option(z[i], z[i]);
}
}
}
The trick was simply to place "variablename.style.display = 'none'/'block';" on the right position. Keep in mind that the code reads from above and for the rest I just used my brain, hehe. I hope this will help anyone who searches for answeres. :)
Try this code
<style>
#sub1, #type1{
display: none;
}
</style>
<select name="main" id="main">
<option value="0" selected>Select Option</option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select name="sub1" id="sub1">
<option value="0" selected>Select Option</option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<select name="type1" id="type1">
<option value="0" selected>Select Option</option>
<option value="value1">value1</option>
<option value="value2">value2</option>
</select>
<script>
var main = document.getElementById('main');
var sub1 = document.getElementById('sub1');
var type1 = document.getElementById('type1');
main.addEventListener('change', function(element){
if(element.target.value == 'value1'){
sub1.style.display = 'block';
}else{
sub1.style.display = 'none';
}
});
sub1.addEventListener('change', function(element){
if(element.target.value == 'value1'){
type1.style.display = 'block';
}else{
type1.style.display = 'none';
}
});
</script>

How do I remove old options in Jquery when parent select box is changed?

I have 3 chained select boxes using jquery and json.
Depending on first 2 values I filter third one my code actually works but the problem is when I change values of first 2 select boxes third select recieves new datas while keeping old ones.
I've tried to empty my array but it didn't work.
$(document).ready(function() {
var json = JSON.parse(jsonString);
var makesArray = [];
var selectedyear;
var selectedcourse;
var $yearDropDown = $("#DropDown_Year");
var $course_type = $("#course_type");
$yearDropDown.change(function() {
selectedyear = this.value;
//filter based on selected year.
});
$course_type.change(function(){
selectedcourse = this.value;
makesArray = jQuery.grep(json, function(course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
for(var i = 0, l = makesArray.length; i < l; i++){
var option = makesArray[i];
selectBox.options.add( new Option(option.course_code, option.course_code, option.course_code) );
}
makesArray= []; //makesArray.empty();
});
});
<div id="DrpDwn">
Year:
<select id="DropDown_Year">
<option>Yıl</option>
<option value="15">2015-2016</option>
<option value="16">2016-2017</option>
</select>
<select class="form-control" id="course_type" name="course_type" required>
<option value="" selected> Choose</option>
<option value="Yos">YÖS</option>
<option value="SatMatGeo">SAT (MAT)</option>
<option value="SatCriRea">SAT (ENG)</option>
<option value="TomerABC">TÖMER (ABC)</option>
<option value="TomerAB">TÖMER (AB)</option>
<option value="TomerBC">TÖMER (BC)</option>
<option value="TomerA1A2">TÖMER (A)</option>
<option value="TomerB1B2">TÖMER (B)</option>
<option value="TomerC1C2">TÖMER (C)</option>
</select>
Make:
<select id="DropDown_Make">
<option>None</option>
</select>
</div>
and this is JSFIDDLE
https://jsfiddle.net/rw7cb8c5/25/
Make DropDown_Make empty using selectBox.innerHTML = "" in $course_type.change() like following.
$course_type.change(function () {
selectedcourse = this.value;
makesArray = jQuery.grep(json, function (course, i) {
return course.course_type == selectedcourse && course.year_code == selectedyear;
})
var selectBox = document.getElementById('DropDown_Make');
selectBox.innerHTML = ""; //added this line
for (var i = 0, l = makesArray.length; i < l; i++) {
var option = makesArray[i];
selectBox.options.add(new Option(option.course_code, option.course_code, option.course_code));
}
makesArray.empty();
});
UPDATED FIDDLE

change de select option value name

I have this html code i want change the value from 0 to usa and from 1 to australia and from 3 to canada i need de name of this value in mysqol database.
thanks
html
<form method="post" id="countriesForm" name="countriesForm" enctype="application/x-www-form-urlencoded">
<select id="select1" name="select1">
<option value="0">USA</option>
<option value="1">AUSTRALIA</option>
<option value="2">CANADA</option>
</select>
</form>
<img id="flags" height="30" width="50" border="0" name="flags"></img>
js
(function(){
var imageArray = new Array("http://www.agem.org/images/flags/united_states.png", "http://www.agem.org/images/flags/australia.png", "http://www.agem.org/images/flags/canada.png");
var altArray = new Array("USA", "AUSTRALIA", "CANADA");
document.getElementById('select1').onchange = function() {
var e = document.getElementById('select1');
var index = e.options[e.selectedIndex].value;
var targetImg = document.getElementById('flags');
targetImg.src = imageArray[index];
targetImg.alt = altArray[index];
};
})();
You can just do this: <option value="usa">USA</option> or you can check in your onSubmit-Listener what the number is and then change the value which should be submitted:
function submit() {
var select1 = document.getElementById('select1');
var index = select1.value;
var country = 'usa';
if(index == 0) {
country = 'usa';
} else if(index == 1) {
country = 'australia';
} else if(index == 2) {
country = 'cananda';
}
}

Creating multiple Select options from an Object

Im stack on creating multiple select options
I have an Object with multi objects inside and want create select options in condition of the previous select option , i provide js fiddle for better understanding .
my objectif is
first select category ----(then)---> select sex -----(then)---> select kind---(then)-->then select size
by this order from that Object.
i could do the select sex and it works but not kind and size.
this is my html
<form name="myform">
<div>
<select name="category_group" id="category_group" >
<option value="0">choose category</option>
<option value='401' > clothes </option>
<option value='403' > shoes </option>
</select>
</div>
<br>
<div>
<select id="clothing_sex" name="clothing_sex" onChange="showclothesKind(this.value,this.form.clothing_kind)">
<option value="0">choose Type»</option>
</select>
<select id="clothing_kind" name="clothing_kind">
<option value="0">choose clothes</option>
</select>
<select id="clothing_size" name="clothing_size">
<option value="0">choose size</option>
</select>
</div>
</form>
and js in the fiddle.
much appreciate your help.
This was kind of fun to play around with. Thanks for posting. I used the following:
var optionTemplate = "<option class='newOption'>sampleText</option>";
$(document).ready(function() {
var removeFromNextSelects = function(firstSelector) {
var selNum = sels.indexOf(firstSelector);
for (var i = selNum; i < sels.length; i++)
{
$(sels[i]).find('.option').remove();
}
};
var populateNextSelect = function(neededObject, targetSelector) {
removeFromNextSelects(targetSelector);
for (var key in neededObject)
{
var name;
neededObject[key].name ? name = neededObject[key].name : name = neededObject[key];
$(targetSelector).append(optionTemplate);
$('.newOption').val(key).html(name).removeClass('newOption').addClass('option');
}
};
var obj1 = {}, obj2 = {}, obj3 = {};
var sels = ["#clothing_sex", "#clothing_kind", "#clothing_size"];
$('#category_group').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[0]);
return;
}
obj1 = {};
var selection = $(this).val();
obj1 = clothes[selection];
populateNextSelect(obj1, sels[0]);
});
$('#clothing_sex').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[1]);
return;
}
obj2 = {};
var selection = $(this).val();
obj2 = obj1[selection].types;
populateNextSelect(obj2, sels[1]);
});
$('#clothing_kind').change(function() {
if ($(this).val() == 0)
{
removeFromNextSelects(sels[2]);
return;
}
obj3 = {};
var selection = $(this).val();
var arr = obj2[selection].sizes;
for (var i = 0; i < arr.length; i++)
{
obj3[Object.keys(arr[i])[0]] = arr[i][Object.keys(arr[i])[0]];
}
populateNextSelect(obj3, sels[2]);
});
});
Here's the fiddle

Categories

Resources