How to add value attribute to option element from array in javascript? - 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>

Related

Not showing all items in JSON

I have created an address selection boxes. If you select a region it will display the provinces included in that region. If I select the province, it will display in the list the municipalities in that province. Lastly, if I select the municipality, it will show the towns included in that municipality. This is working fine for the first 5 regions. But for the rest, it works only for the region and province. This is the live demo --> https://ar-ey.github.io/phplaces/
Here is my html code:
<body>
<select name="regions" id="regions">
<option value="" disabled selected>Select</option>
</select><br>
<select name="provinces" id="provinces">
<option value="" disabled selected>Select</option>
</select><br>
<select name="" id="municipalities">
<option value="" disabled selected>Select</option>
</select><br>
<select name="" id="barangays">
<option value="" disabled selected>Select</option>
</select><br>
<script src="./app.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here is the javascript code:
// get first dropdown and bind change event handler
$('#regions').change(function() {
// get optios of second dropdown and cache it
var $options = $('#provinces')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
$('#provinces').change(function() {
// get optios of second dropdown and cache it
var $options = $('#municipalities')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
})
$('#municipalities').change(function() {
// get optios of second dropdown and cache it
var $options = $('#barangays')
// update the dropdown value if necessary
.val('')
// get options
.find('option')
// show all of the initially
.show();
// check current value is not 0
if (this.value != '0')
$options
// filter out options which is not corresponds to the first option
.not('[data-val="' + this.value + '"],[data-val=""]')
// hide them
.hide();
})
})
let regions = [];
let provinces = [];
let municipalities = [];
let barangays = [];
function showRegions(){
const dropdown = document.getElementById('regions')
for (var i = 0; i < regions.length; i++) {
var option = document.createElement("option");
option.value = regions[i].regCode;
option.text = regions[i].regDesc;
dropdown.appendChild(option);
}
}
function showProvinces(){
const dropdown = document.getElementById('provinces')
for (var i = 0; i < provinces.length; i++) {
var option = document.createElement("option");
option.value = provinces[i].provCode;
option.text = provinces[i].provDesc;
option.setAttribute('data-val',provinces[i].regCode);
dropdown.appendChild(option);
}
}
function showMunicipalities(){
const dropdown = document.getElementById('municipalities')
for (var i = 0; i < municipalities.length; i++) {
var option = document.createElement("option");
option.value = municipalities[i].citymunCode;
option.text = municipalities[i].citymunDesc;
option.setAttribute('data-val',municipalities[i].provCode)
dropdown.appendChild(option);
}
}
function showBarangays(){
const dropdown = document.getElementById('barangays')
for (var i = 0; i < barangays.length; i++) {
var option = document.createElement("option");
option.value = barangays[i].brgyCode;
option.text = barangays[i].brgyDesc;
option.setAttribute('data-val',barangays[i].citymunCode)
dropdown.appendChild(option);
}
}
fetch("./json/refregion.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
regions = data.RECORDS;
showRegions()
})
fetch("./json/refprovince.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
provinces = data.RECORDS;
showProvinces()
})
fetch("./json/refcitymun.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
municipalities = data.RECORDS;
showMunicipalities()
})
fetch("./json/refbrgy.json")
.then(function(resp){
return resp.json();
})
.then(function(data){
console.log(data)
barangays = data.RECORDS;
showBarangays()
})

How to Get the Result Using Javascript

I am working with this code and would like to get the result inside intTotal. But it doesn't give me the result I wish.
window.onload = function() {
var intNum = document.getElementById("intNum");
for (var i = 1; i <= 3000; i++) {
var option = document.createElement("option");
option.innerHTML = i;
option.value = i;
intNum.appendChild(option);
}
};
function jml_total() {
var hrg_sat = parseInt(document.querySelector("hrg_sat").innerHTML);
var jml_pilih = parseInt(document.getElementById("intNum").value);
var int_hitung = hrg_sat * jml_pilih;
document.getElementById("intTotal").value = int_hitung;
}
<div id="hrg_sat">3000</div>
<select id="intNum" onChange="jml_total(this.value)">
<option value="" disabled selected>Pilih Jumlah ... </option>
</select>
<br />
<div id="intTotal"></div>
I tried this thread. Or, you have the simplest one, but not using jquery.
You need to specify that hrg_sat is an id on your querySelector by using # as prefix
var hrg_sat = parseInt(document.querySelector("#hrg_sat").innerHTML);
Also, as the previous answer has mentioned, you need to use innerHTML property instead of value to display the text on the DOM on a <div> element
window.onload = function() {
var intNum = document.getElementById("intNum");
for (var i = 1; i <= 3000; i++) {
var option = document.createElement("option");
option.innerHTML = i;
option.value = i;
intNum.appendChild(option);
}
};
function jml_total() {
var hrg_sat = parseInt(document.querySelector("#hrg_sat").innerHTML);
var jml_pilih = parseInt(document.getElementById("intNum").value);
var int_hitung = hrg_sat * jml_pilih;
document.getElementById("intTotal").innerHTML = int_hitung;
}
<div id="hrg_sat">3000</div>
<select id="intNum" onChange="jml_total(this.value)">
<option value="" disabled selected>Pilih Jumlah ... </option>
</select>
<br />
<div id="intTotal"></div>
Since intTotal is a div, you want to use innerHTML not value. value in the post you linked to is for an input control, not a div
document.getElementById("intTotal").innerHTML = 'your content goes here';
<div id="intTotal"></div>

Creating an object every time I call a function

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.

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

disable checkbox when i select

i have a problem in html and javascript. i have tried different approach but everything didnt worked. so this is my sample code.
<select id = "testselect" name = "testselect">
<option> </option>
<option id = "o1" name = "testselect" value = "1" onselect='document.getElementById("os1").disabled = true;'> 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>
ok, that's the code. what i want to happen is, when i selected o1(option id), os1(checkbox id) must be disabled and when i selected o2(option id), os2(checkbox id) must be disabled, and so on. so can anyone help me?
Try this:
Using plain javascript:
var select;
function changeIt() {
var allCheckboxes = document.querySelectorAll('input[type=checkbox]');
for (var i = 0; i < allCheckboxes.length; i++) {
allCheckboxes[i].removeAttribute('disabled');
}
var value = select.options[select.selectedIndex].value;
var checkBox = document.querySelector('input[id=os' + value + ']');
checkBox.disabled = true;
}
window.onload = function () {
select = document.getElementById('testselect');
select.onchange = changeIt;
changeIt();
}
Demo
Using jQuery:
$('select').change(function () {
$('input[type=checkbox]').removeAttr('disabled');
$('input[id=os' + this.value + ']').attr('disabled', true);
});
Demo
My own suggestion would be to move the event-handling outside of the HTML (for ease of future maintenance and change), and take the following approach:
function disableCheck(event) {
// get the element that was the target of the 'change' event:
var that = event.target,
/* find the option tags, and retrieve the option that was selected
from that collection (nodeList) of elements: */
opt = that.getElementsByTagName('option')[that.selectedIndex];
/* find the element whose 'id' is equal to the 'id' of the 'option'
once the 's' is inserted, and set the 'disabled' property to 'true': */
document.getElementById(opt.id.replace('o', 'os')).disabled= true;
}
// bind the onchange event-handler to the element with the id of 'testselect':
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
To toggle which elements are disabled (rather than simply increase the number of disabled elements):
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o','os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++){
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
Well, this is ugly...and suggests I really need to rethink the approach above, however it does work (though it doesn't properly support IE as yet). This uses a trigger function which is fired upon the window.load event which triggers the change event from the select element-node:
function trigger(event, source) {
var newEvent;
if (document.createEvent) {
newEvent = document.createEvent("HTMLEvents");
newEvent.initEvent(event, true, true);
} else {
newEvent = document.createEventObject();
newEvent.eventType = event;
}
newEvent.eventName = event;
if (document.createEvent) {
source.dispatchEvent(newEvent);
} else {
source.fireEvent("on" + newEvent.eventType, newEvent);
}
}
function disableCheck(event) {
var that = event.target,
opt = that.getElementsByTagName('option')[that.selectedIndex],
idToFind = opt.id.replace('o', 'os'),
allInputs = document.getElementsByTagName('input');
for (var i = 0, len = allInputs.length; i < len; i++) {
if (allInputs[i].type == 'checkbox') {
allInputs[i].disabled = allInputs[i].id === idToFind;
}
}
}
window.addEventListener('load', function(){
trigger('change', document.getElementById('testselect'));
});
document.getElementById('testselect').onchange = disableCheck;
JS Fiddle demo.
onselect should go into the select
<script>
function onSelect(obj){
var x = document.getElementsByName("othser[]");
for (var i in x) x[i].disabled = false;
document.getElementById("os"+obj.value).disabled=true;
}
</script>
<select id = "testselect" name = "testselect" onchange='onSelect(this)'>
<option> </option>
<option id = "o1" name = "testselect" value = "1" > 1 </option>
<option id = "o2" name = "testselect" value = "2" > 2 </option>
<option id = "o3" name = "testselect" value = "3"> 3 </option>
</select>
<div >
<input id = "os1" type="checkbox" name="othser[]" value="7000" />cb1<br/>
<input id = "os2" type="checkbox" name="othser[]" value="7001"/>cb2<br/>
<input id = "os3" type="checkbox" name="othser[]" value="7002"/>cb3<br/>
</div>

Categories

Resources