let StatusData = {
"lawfull resident" : ["renewal of green card", "applying for citizenship"],
}
window.onload = function(){
let statusSelection = document.querySelector("#UserStatus");
let conditionSelection = document.querySelector("#Condition");
for(let userstats in StatusData){
statusSelection.options[statusSelection.options.length] = new Option(
userstats,
userstats
);
};
statusSelection.onchange = (e) =>{
for(let usercondition in StatusData[e.target.value]){
conditionSelection.options[conditionSelection.options.length] = new Option(
usercondition,
usercondition
);
};
};
};
once the first option is elected, the second selected will display the values of that particular option
Related
I want my filters variable to update, my guess is it's re-initializing as the set value every time the function is called, whenever i try to declare it outside of the function I get a lexical error, how can I make sure it keeps the value assigned to it after a button has clicked
export function categoryRender(){
let filter = 'RICK'
console.log(filter)
const all = document.getElementById('all');
all.onclick = function(){
filter = 'ALL'
render(filter);
}
categories = categories.sort();
const filterContainer = document.getElementById("filter-container");
filterContainer.innerHTML = "";
const allFilterImg = document.getElementById('all-image');
if (filter === 'ALL'){
allFilterImg.setAttribute('src', './images/checked.jpeg')
}else{
allFilterImg.setAttribute('src', './images/unchecked.png')
console.log('unchecked all firing')
}
for (let i = 0; i < categories.length; i++){
const line = document.createElement("span");
const filterButton = document.createElement("img");
const filterLabel = document.createElement("h2");
filterContainer.appendChild(line);
line.appendChild(filterButton);
line.appendChild(filterLabel);
line.setAttribute('id', categories[i]);
line.classList.add('filter-line');
filterLabel.innerHTML = categories[i];
if (filter === categories[i]){
filterButton.setAttribute('src', './images/checked.jpeg')
}else{
filterButton.setAttribute('src', './images/unchecked.png')
}
line.onclick = function(){
filter = categories[i];
render(filter)
}
}
}
My goal is to build a large array of data that has both text and numbers, and the text is randomly selected from a preselected array of names (first and last name). Function start() is activated with a button.
var malenames = ["John", "Bob", "Jim","Tim","Skylar","Zach","Jacob"];
var maleLast = ["J.","M.","B.","D.","W."];
var males = new Array();
males[0] = new Array("Placeholder","Placeholder",18);
males[1] = new Array("Placeholder","Placeholder",18);
males[2] = new Array("Placeholder","Placeholder",18);
males[3] = new Array("Placeholder","Placeholder",18);
males[4] = new Array("Placeholder","Placeholder",18);
males[5] = new Array("Placeholder","Placeholder",18);
males[6] = new Array("Placeholder","Placeholder",18);
males[7] = new Array("Placeholder","Placeholder",18);
males[8] = new Array("Placeholder","Placeholder",18);
males[9] = new Array("Placeholder","Placeholder",18);
function start() {
localStorage.setItem("random", Math.floor((Math.random()*(100-0))));
span.textContent = localStorage.getItem("random");
var i;
var j;
for (i=0; i < males.length; i++) {
males[i][0] = malenames[Math.floor(Math.random()*malenames.length)];
localStorage.setItem("males", JSON.stringify(males));
}
for (j=0; j<males.length; j++) {
males[j][1] = maleLast[Math.floor(Math.random()*maleLast.length)];
localStorage.setItem("males", JSON.stringify(males));
}
firstN.textContent = males[0][0];
lastN.textContent = males[0][1];
age.textContent = males[0][2];
}
This code successfully randomizes and then saves the first and last names into the array in localStorage. However, I am wanting to modify the number 18 on a timer by adding a value to it every so many seconds.
setInterval(function(){
var k;
for(k=0;k<males.length;k++){
males[k][2]++;
localStorage.setItem("males",JSON.stringify(males));
}
age.innerHTML = males[0][2];
}, 3000);
Everything works just fine and everything gets stored into localStorage until I refresh the page. When I refresh the page, the localStorage array is still correct until the interval occurs. When this happens, the arrays refresh back to [Placeholder, Placeholder, 18]. I am curious as to why the code does this when I am only trying to add to the age variable every interval. I would gladly accept feedback and explanations into understanding this. Thank you.
Maybe you really want to do something more like:
function shuffle(a){
a.sort(function(b, c){
return 0.5 - Math.random();
});
}
function RandomPeople(lastNameArray, firstNameArray){
var t = this;
this.lastNames; this.firstNames;
this.make = function(){
this.lastNames = lastNameArray.slice(); this.firstNames = firstNameArray.slice();
this.people = []; shuffle(this.firstNames);
this.firstNames.forEach(function(n){
t.people.push([t.lastNames[Math.floor(Math.random()*t.lastNames.length)], n, 18]);
});
return this;
}
this.grab = function(){
if(localStorage.people){
return JSON.parse(localStorage.people);
}
return false;
}
this.save = function(){
localStorage.people = JSON.stringify(this.people);
return this;
}
}
var men = new RandomPeople(['J.', 'M.', 'B.', 'D.', 'W.'], ['John', 'Bob', 'Jim', 'Tim', 'Skylar', 'Zach', 'Jacob']);
var peps = men.grab();
if(!peps){
men.make(); peps[5][2] += 2; men.save(); peps = men.people;
}
console.log(peps);
I have a simple TODO app written in vanilla javascript. Here is the application:
Issue/Problem that I am having at this point is:
When I click New todo button the existing checked state of the checkbox disappears.
I am not sure how to persist the checkbox state after prompt window OK click. Please find the source code below.
const classNames = {
TODO_ITEM: 'todo-container',
TODO_CHECKBOX: 'todo-checkbox',
TODO_TEXT: 'todo-text',
TODO_DELETE: 'todo-delete',
}
const checkbox = document.createElement( "input" );
checkbox.type = "checkbox"
checkbox.id = classNames.TODO_CHECKBOX
const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')
function newTodo() {
let newTodo = prompt("Please enter a todo item");
if(newTodo){
itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
list.append(checkbox)
list.innerHTML += "<li>" + newTodo
}
let allCheckBoxes = document.querySelectorAll("input[id='todo-checkbox']");
uncheckedCountSpan.innerHTML = allCheckBoxes.length
console.log(allCheckBoxes.length)
for(let i = 0; i < allCheckBoxes.length; i++){
allCheckBoxes[i].onclick = function() {
if ( this.checked ) {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
}
else {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
}
};
}
}
Please let me know if you have any thoughts/directions.
Thanks in advance.
You have two issues: first, you're appending the same checkbox every time. Second, you are directly editing innerHTML, which is forcing the DOM to re-render everything, reverting the state of the inputs. Here's how I would do it:
const classNames = {
TODO_ITEM: 'todo-container',
TODO_CHECKBOX: 'todo-checkbox',
TODO_TEXT: 'todo-text',
TODO_DELETE: 'todo-delete',
}
const list = document.getElementById('todo-list')
const itemCountSpan = document.getElementById('item-count')
const uncheckedCountSpan = document.getElementById('unchecked-count')
function newTodo() {
let newTodo = prompt("Please enter a todo item");
if(!newTodo){
return
}
itemCountSpan.innerHTML = parseInt(itemCountSpan.innerHTML) + 1
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
const checkbox = document.createElement( "input" );
checkbox.onclick = function() {
if ( this.checked ) {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) - 1
}
else {
uncheckedCountSpan.innerHTML = parseInt(uncheckedCountSpan.innerHTML) + 1
}
};
checkbox.type = "checkbox"
checkbox.class = classNames.TODO_CHECKBOX
list.append(checkbox)
const listItem = document.createElement("li")
listItem.innerHTML = newTodo
list.append(listItem)
}
Note that I also replaced the id of the checkbox with a class - there are multiple checkboxes, and ids should be unique.
Good day
My code below populate the lists of warehouses to a dropdown, which is what i want but i also want do make the warehouse with isMainWarehouse = true a default selected when populating the warehouses (note that there is only one main warehouse)
function PopulateWarehouses() {
var warehouseDropDown = document.getElementById('SelectWarehouse');
var warehouseFragment = document.createDocumentFragment();
_warehouseRepository.getWarehouses().done(function (data) {
for (var element in data.items) {
if (data.items.hasOwnProperty(element)) {
var recievedData = data.items[element];
var id = recievedData.id;
var name = recievedData.warehouseName;
var main = recievedData.isMainWarehouse;
var opt = document.createElement('option');
opt.innerHTML = name;
opt.value = id;
warehouseFragment.appendChild(opt);
}
}
warehouseDropDown.appendChild(warehouseFragment);
$('#SelectWarehouse').selectpicker('refresh');
});}
here is my dropdown
<select id="SelectWarehouse" name="SelectWarehouse" class="selectpicker show-tick form-control" data-live-search="true"></select>
This method just get the list of all the warehouses
// GET: get list of all warehouses
public async Task<ListResultOutput<WarehouseListDto>> GetWarehouses()
{
var warehouses = await _warehouseRepository.GetAllListAsync();
ListResultOutput<WarehouseListDto> dto = new ListResultOutput<WarehouseListDto>(
warehouses
.OrderBy(t => t.WarehouseName)
.ToList()
.MapTo<List<WarehouseListDto>>()
);
return dto;
}
To select the main one, you just need to set the selected property of the option for the main warehouse
function PopulateWarehouses() {
var warehouseDropDown = document.getElementById('SelectWarehouse');
var warehouseFragment = document.createDocumentFragment();
_warehouseRepository.getWarehouses().done(function (data) {
for (var element in data.items) {
if (data.items.hasOwnProperty(element)) {
var recievedData = data.items[element];
var id = recievedData.id;
var name = recievedData.warehouseName;
var main = recievedData.isMainWarehouse;
var opt = document.createElement('option');
opt.innerHTML = name;
if(main){
opt.selected = 'selected';
}
opt.value = id;
warehouseFragment.appendChild(opt);
}
}
warehouseDropDown.appendChild(warehouseFragment);
$('#SelectWarehouse').selectpicker('refresh');
});}
I am trying to Create Cascading data table using java script but it's not printing data properly.
I want to crete drop down when I select asset from dropdown , it load all section name from that asset and when I select sections fron thier child it select Ultrasonic sections name.
Also in asset it's populating 4 time "asset 4". It should print 1 time only.
I tried to debuge but it's not working . can any one help me?
And I want to do this in JavaScript only
JAVASCRIPT
var stateObject = '{"uri": "/assets/4afd3544-cea1-363d-ba29 e39831d8930d","name": "Asset 4","sections": [{"uri": "/assets/2dc11152-7b85- 35d7-8af6-c48ca4397d9f","sectionId": null, "name": "Section 1","ultrasonicSensors": null,"temperatureSensors": null,"ultrasonicSensorPositions": [{"ultrasonicSensorPositionId":"1395","sensorPositionName":"MeasurementPosition 1","diameter": "0","rotation": "0","sequenceNumber": null, "sectionId": "/assets/2dc11152-7b85-35d7-8af6-c48ca4397d9f"}]}]}';
var json = JSON.parse(stateObject);
window.onload = function () {
var stateSel = document.getElementById("stateSel"),
countySel = document.getElementById("countySel"),
citySel = document.getElementById("citySel");
for (state in json) {
stateSel.options[stateSel.options.length] = new Option(json.name , "");
}
stateSel.onchange = function () {
countySel.length = 1; // remove all options bar first
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) {
countySel.options[0].text = "Please select state first"
citySel.options[0].text = "Please select county first"
return; // done
}
countySel.options[0].text = "Please select county"
var x = JSON.stringify(json.sections);
// alert(x)
for (var county in x) {
countySel.options[countySel.options.length] = new Option(county, x);
}
if (countySel.options.length==2) {
countySel.selectedIndex=1;
countySel.onchange();
}
}
stateSel.onchange(); // reset in case page is reloaded
countySel.onchange = function () {
citySel.length = 1; // remove all options bar first
if (this.selectedIndex < 1) {
citySel.options[0].text = "Please select county first"
return; // done
}
citySel.options[0].text = "Please select city"
var cities = stateObject[stateSel.value][this.value];
for (var i = 0; i < cities.length; i++) {
citySel.options[citySel.options.length] = new Option(cities[i], cities[i]);
}
if (citySel.options.length==2) {
citySel.selectedIndex=1;
citySel.onchange();
}
}
}
Here is js fiddle demo