I have form that select User ID among Users.
<select>
<option value="">Tabs User</option>
<option value="ID3357">ID3357</option>
<option value="ID2695">ID2695</option>
<option value="ID1072">ID1072</option>
<option value="ID1306">ID1306</option>
<option value="ID2702">ID2702</option>
The First name of the users:
ID2695 Jacob
ID1072 Moe
ID1306 sara
ID2702 Sam
how to show the Firstname of ID below the form, when the enduser pick the ID in form.
this code might help,
<!DOCTYPE html>
<html>
<body>
<h1 id="name"></h1>
<select onchange="getUser(this.value)">
<option disabled selected value>-</option>
<option value="ID3357">ID3357</option>
<option value="ID2695">ID2695</option>
<option value="ID1072">ID1072</option>
<option value="ID1306">ID1306</option>
<option value="ID2702">ID2702</option>
</select>
<script type="text/javascript">
var users = [
{ id: "ID2695", firstName: "Jacob" },
{ id: "ID1072", firstName: "Moe" },
{ id: "ID1306", firstName: "Sara" },
{ id: "ID2702", firstName: "Sam" },
{ id: "ID3357", firstName: "Someone" }
];
function getUser(uid) {
var [{ firstName }] = users.filter(({id}) => id === uid);
document.getElementById("name").textContent = firstName;
}
</script>
</body>
</html>
Explanation: The users are hard-coded into the js as objects with and id and username. As soon as somebody picks a value from the dropdown, js gets the value from the dropdown input and filters the array + selects the firstName from the returned array of an object. Then it displays that into the h1. As simple as that.
Related
I want to make a select form in HTML that checks that displays a secondary select group if certain options in the first select group are selected
<body>
<form name="Test">
<!-- all the factors to account for when calculating odds-->
<div>
<label>
<select name="FirstList" id="FirstListID">
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select><br>
<!-- SecondList would be visible if "1" is selected-->
<label name="SecondList" style="display:none">List for "1":
<select name="SecondListSelect" id="SecondListSelectID">
<option value="3">Placeholder</option>
</select><br>
</label>
<!-- ThirdList would be visible if "2" is selected-->
<label name="ThirdList" style="display:none">List for "2":
<select name="ThirdListSelect" id="ThirdListSelectID">
<option value="4">Placeholder</option>
</select><br>
</label>
<!-- No secondary select form appears if "3" is selected-->
</div>
</form>
</body>
I've tried using AddEventListeners but the code doesn't appear that maintainable since I plan on adding more options in the primary drop down menu so I would need to constantly add what secondary select groups appear based on what primary option is selected. How could I go about coding this in JS?
Give each <label> an identifier tying it to the value for which it should be visible. A data attribute would work. Then, whenever the <select> changes, iterate over all such labels and hide them. Take the .value from the select and use string concatenation to construct a selector for the element with that in the dataset, and then you can select that element and show it.
For example, with labels like
<label data-option=1>
you could have
for (const label of document.querySelectorAll('[data-option]')) {
label.style.display = 'none';
}
document.querySelector(`[data-option=${select.value}]`).style.display = 'block';
inside the change listener.
Store the options of the second <select> element in an object. Make sure the keys match the value attribute value of the options in the first <select>.
Listen for a change event on the first <select>. Whenever a change happens, empty the options of the second <select>, get the new options from the object and create new <option> elements with that data.
Now you have a dynamic <select> element that is easy to scale.
const optionData = {
'1': [
{
label: 'Foo',
value: 'foo',
}
],
'2': [
{
label: 'Bar',
value: 'bar',
},
{
label: 'Baz',
value: 'baz',
}
],
'3': [
{
label: 'Hello',
value: 'hello',
},
{
label: 'World',
value: 'world',
}
]
};
const firstList = document.querySelector('#first-list');
const secondList = document.querySelector('#second-list');
function removeOptions(selectElement) {
for (let i = selectElement.options.length - 1; i >= 0; i--) {
selectElement.remove(i);
}
}
// Update the second `<select>` based on the first's selection.
firstList.addEventListener('change', event => {
const value = event.target.value;
const options = optionData[value];
removeOptions(secondList);
for (const { label, value } of options) {
const option = new Option(label, value);
secondList.add(option);
}
});
<label for="first-list">List One</label>
<select name="first-list" id="first-list">
<option value="" selected disabled>Make a selection</option>
<option value="1">First option</option>
<option value="2">Second option</option>
<option value="3">Third option</option>
</select>
<label for="second-list">List Two</label>
<select name="second-list" id="second-list">
<option value="" selected disabled>No options yet</option>
</select>
You could build the selectors from your js file:
const optionGroups = {
"first": [
{ "text": "for first - 1", "value": 1 }
],
"second": [
{ "text": "for second - 1", "value": 1 },
{ "text": "for second - 2", "value": 2 }
],
"third": [
{ "text": "for third - 1", "value": 1 },
{ "text": "for third - 2", "value": 2 },
{ "text": "for third - 3", "value": 3 }
]
},
mainSelect = document.querySelector('#mainSelect'),
secondarySelect = document.querySelector('#secondarySelect');
async function startWithMainSelect()
{
for (let key of Object.keys(optionGroups))
{
const option = new Option(key);
mainSelect.appendChild(option);
}
onChangeMainSelect();
}
function onChangeMainSelect()
{
while (secondarySelect.firstChild)
secondarySelect.firstChild.remove();
for (let _option of optionGroups[mainSelect.value])
{
const option = new Option(_option.text, _option.value);
secondarySelect.appendChild(option);
}
}
mainSelect.addEventListener('change', onChangeMainSelect);
startWithMainSelect();
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>replit</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h4>Main:</h4>
<select id="mainSelect"></select>
<br>
<h4>Secondary:</h4>
<select id="secondarySelect"></select>
<script src="https://replit.com/public/js/replit-badge.js" theme="blue" defer></script>
<script src="script.js"></script>
</body>
</html>
If there were a lot of options, you could move them into a json file and request them from there. Here's an example.
I am a complete beginner making a site for fun/skill development. I saw this code snippet online for cascading dropdowns, but when I run the below code, the form value for "First" comes through as the index number for the value I see in the dropdown (eg. Meals comes through as a 1).
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script>
let data = [{
item: 'Fruits',
subitems: ['apple', 'banana', 'pineapple', 'watermelon']
},
{
item: 'Meals',
subitems: ['chicken', 'bacon', 'pork', 'beef']
},
{
item: 'Animals',
subitems: ['cat', 'rabbit', 'mouse', 'lion']
},
{
item: 'Brands Laptops',
subitems: ['Dell', 'HP', 'Apple', 'Sony'],
},
];
window.onload = function() {
var itemSel = document.getElementById("first");
var subitemSel = document.getElementById("seconda");
var subitem2Sel = document.getElementById("secondb")
for (var x in data) {
itemSel.options[itemSel.options.length] = new Option(data[x].item, x);
}
itemSel.onchange = function() {
//empty
subitemSel.length = 1;
subitem2Sel.length = 1;
//display correct values
for (var y of data[this.value].subitems) {
subitemSel.options[subitemSel.options.length] = new Option(y, y);
}
for (var z of data[this.value].subitems) {
subitem2Sel.options[subitem2Sel.options.length] = new Option(z, z);
}
}
}
</script>
</head>
<body>
<h1>Cascading Dropdown Example</h1>
<form name="form1" id="form1" action="/action_page.php">
First:
<select name="first" id="first">
<option value="" selected="selected">Select type</option>
</select>
<br><br> Second A:
<select name="seconda" id="seconda">
<option value="" selected="selected">Please select first</option>
</select>
<br><br> Second B:
<select name="secondb" id="secondb">
<option value="" selected="selected">Please select first</option>
</select>
<br><br>
<input type="submit" value="Submit">
</form>
</body>
I know how to alter the code to get the value of First to come through as the text, but that then messes up the cascading dropdowns. How can I get the form, upon hitting submit, to give me the text value from "First" and not the index number of whatever is selected?
I have an array of objects which looks like this
[
{
id: 101,
name: 'Alex',
tg: 'REV001',
eng: 'IP'
},
{
id: 102,
name: 'Bob',
tg: 'REV002',
eng: 'CAD'
},
{
id: 103,
name: 'Carl',
tg: 'REV001',
eng: 'OPP'
},
{
id: 104,
name: 'Dave',
tg: 'REV003',
eng: 'IP'
},
{
id: 105,
name: 'Jeffry',
tg: 'REV005',
eng: 'OPP'
},
]
I also have 3 select box which is like
// Name select
<select>
<option value="">All</option>
<option value="Alex">Alex</option>
<option value="Bob">Bob</option>
<option value="Carl">Carl</option>
<option value="Dave">Dave</option>
<option value="Jeffry">Jeffry</option>
</select>
// TG select
<select>
<option value="">All</option>
<option value="REV001">REV001</option>
<option value="REV002">REV002</option>
<option value="REV003">REV003</option>
<option value="REV005">REV005</option>
</select>
// ENG select
<select>
<option value="">All</option>
<option value="IP">IP</option>
<option value="CAD">CAD</option>
<option value="OPP">OPP</option>
</select>
These select box shows all possible values present in array, categorized based on Name, TG and ENG.
I want to filter the data based on the selection of option from these select input.
For example,
If I have Name as all, ENG as all and TG as REV001 then it should filter data array and get a new array with only objects having TG as REV001.
I already have events calls for value change, just want logic to how to filter data based on selected options. A function which should return a new array of filtered data from original data.
I tried to create a variable like
filteredSearch: any = {
NAME: 'All',
ENG: 'All',
TG: 'All'
}
and wrote a method like
onFilterSearch() {
this.filteredList = [];
this.requestData.forEach(element => {
for (let key in this.filteredSearch) {
if (!(this.filteredSearch[key] === '')) {
if (element.header[key].includes(this.filteredSearch[key])) {
this.filteredList.push(element);
}
}
}
});
}
I am changing filteredSearch as the select input get changed and calling the onFilterSearch(). But this didn't work for me, maybe I am missing something here.
Please find the logic and the code snippet below:
Logic:
var filteredData = data.filter(e => {
return (!nameSelect || e.name === nameSelect) && (!tgSelect || e.tg === tgSelect) && (!engSelect || e.eng === engSelect);
});
Code Snippet:
// Name select
<select id="nameSelect">
<option value="">All</option>
<option value="Alex">Alex</option>
<option value="Bob">Bob</option>
<option value="Carl">Carl</option>
<option value="Dave">Dave</option>
<option value="Jeffry">Jeffry</option>
</select>
// TG select
<select id="tgSelect">
<option value="">All</option>
<option value="REV001">REV001</option>
<option value="REV002">REV002</option>
<option value="REV003">REV003</option>
<option value="REV005">REV005</option>
</select>
// ENG select
<select id="engSelect">
<option value="">All</option>
<option value="IP">IP</option>
<option value="CAD">CAD</option>
<option value="OPP">OPP</option>
</select>
<br/>
<button id="filterBtn" type="button">Filter</button>
<script>
var data = [
{
id: 101,
name: 'Alex',
tg: 'REV001',
eng: 'IP'
},
{
id: 102,
name: 'Bob',
tg: 'REV002',
eng: 'CAD'
},
{
id: 103,
name: 'Carl',
tg: 'REV001',
eng: 'OPP'
},
{
id: 104,
name: 'Dave',
tg: 'REV003',
eng: 'IP'
},
{
id: 105,
name: 'Jeffry',
tg: 'REV005',
eng: 'OPP'
},
];
function filterData(data) {
var nameSelect = document.getElementById("nameSelect");
nameSelect = nameSelect.options[nameSelect.selectedIndex].value;
var tgSelect = document.getElementById("tgSelect");
tgSelect = tgSelect.options[tgSelect.selectedIndex].value;
var engSelect = document.getElementById("engSelect");
engSelect = engSelect.options[engSelect.selectedIndex].value;
var filteredData = data.filter((e) => {
return (!nameSelect || e.name === nameSelect) && (!tgSelect || e.tg === tgSelect) && (!engSelect || e.eng === engSelect);
});
console.log(filteredData);
}
document.getElementById("filterBtn").addEventListener("click", e => {
filterData(data);
});
</script>
This solution could be made more robust by defining currentFilter as an object instead of an array (and by building the <select> elements in JavaScript from their respective lists to ensure that the HTML is never out of sync with the script), but it handles your use case as-is.
// Defines globals
const lists = {
name: "Alex,Bob,Carl,Dave,Jeffry".split(","),
tg: "REV001,REV002,REV003,REV004,REV005".split(","),
eng: "IP,CAD,OPP".split(",")
};
let data = [
{ id: 101, name: 'Alex', tg: 'REV001', eng: 'IP' },
{ id: 102, name: 'Bob', tg: 'REV002', eng: 'CAD' },
{ id: 103, name: 'Carl', tg: 'REV001', eng: 'OPP' },
{ id: 104, name: 'Dave', tg: 'REV003', eng: 'IP' },
{ id: 105, name: 'Jeffry', tg: 'REV005', eng: 'OPP' },
];
const dropdowns = document.getElementsByClassName("filterable");
// Runs the `filterData` function when the user changes something
document.addEventListener("change", filterData);
// Defines the `filterData` function
function filterData(event){
// Converts the NodeList to an Array so we can use the `.includes`,
// `.map`, and `.filter` methods
const dropdownArr = Array.from(dropdowns);
// Makes sure the changed element was one we care about before proceeding
if(dropdownArr.includes(event.target)){
// Makes a new array from the selected values
const currentFilter = dropdownArr.map(dropdownArr => dropdownArr.value);
// Makes a new (filtered) array by applying each element of `currentFilter`
// to its respective property in each element of `data`
// (This is the fragile bit because it assumes the order is correct.)
const output = data.filter(item =>
(!currentFilter[0] || currentFilter[0] == item.name) &&
(!currentFilter[1] || currentFilter[1] == item.tg) &&
(!currentFilter[2] || currentFilter[2] == item.eng)
);
// Does something with the filtered data
console.log(output.length > 0 ? output : "No matching results");
}
}
<select id="name" class="filterable">
<option value="">All</option>
<option value="Alex">Alex</option>
<option value="Bob">Bob</option>
<option value="Carl">Carl</option>
<option value="Dave">Dave</option>
<option value="Jeffry">Jeffry</option>
</select>
<select id="tg" class="filterable">
<option value="">All</option>
<option value="REV001">REV001</option>
<option value="REV002">REV002</option>
<option value="REV003">REV003</option>
<option value="REV005">REV005</option>
</select>
<select id="eng" class="filterable">
<option value="">All</option>
<option value="IP">IP</option>
<option value="CAD">CAD</option>
<option value="OPP">OPP</option>
</select>
I have three variables in my maincontroller, one for select person, one for genre associated with selected person name, and an array of objects with data. I bind the data together in select element enviroment, but now my goal is to output selected items in paragraph for further manipulation, i managed to output selected person but it appears in vertical aligment. Can someone show me how to output for example in my case let's say this, I select Chris and in my paragraph I want to get "Genre that Chris listen are Indie, Drumstep, Dubstep and Electro"
myApp.controller('mainController', function($scope){
$scope.selectedPerson = 0;
$scope.selectedGenre = null;
$scope.people = [
{ id: 0, name: 'Leon', music: [ 'Rock', 'Metal', 'Dubstep', 'Electro' ] },
{ id: 1, name: 'Chris', music: [ 'Indie', 'Drumstep', 'Dubstep', 'Electro' ] },
{ id: 2, name: 'Harry', music: [ 'Rock', 'Metal', 'Thrash Metal', 'Heavy Metal' ] },
{ id: 3, name: 'Allyce', music: [ 'Pop', 'RnB', 'Hip Hop' ] }
];
});
HTML Template
<!DOCTYPE html>
<head>
<title>Learning AngularJS</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js" type="text/javascript"></script>
<script type="text/javascript" src='app.js'></script>
<script type="text/javascript" src='maincontroller.js'></script>
</head>
<body>
<div id='content' ng-app='myAng' ng-controller='mainController'>
<select ng-model='selectedPerson' ng-options='list.name for list in people'></select>
<select ng-model='selectedGenre'>
<option ng-repeat='genre in people[selectedPerson.id].music'>{{genre}}</option>
</select>
<p ng-model='people' ng-repeat='person in people[selectedPerson.id].name'>{{person}}</p>
</div>
</body>
</html>
i managed to output selected person but it appears in vertical aligment.
You run ng-repeat directive on single String. this is a reason why you get something like:
C
h
r
i
s
Maybe something like:
<p>Genre that {{people[selectedPerson.id].name}} listen are {{people[selectedPerson.id].music.join(', ')}}<p>
Demo
<select ng-model='selectedPerson' ng-options='list as list.name for list in people'>
<option value="">-- Select Person --</option>
</select>
<select ng-model='selectedGenre'>
<option ng-repeat='genre in people[selectedPerson.id].music'>{{genre}}</option>
</select>
<p>Genre that {{people[selectedPerson.id].name}} listen are {{people[selectedPerson.id].music.join(', ')}}<p>
Let's say I have a list of selects that are all named batters[] which are all identical lists. Sample code might be:
<select name="batters[]">
<option value="945">Bobby Abreu</option>
<option value="808">Erick Almonte</option>
</select>
<select name="batters[]">
<option value="945">Bobby Abreu</option>
<option value="808">Erick Almonte</option>
</select>
<select name="batters[]">
<option value="945">Bobby Abreu</option>
<option value="808">Erick Almonte</option>
</select>
... and so forth.
I want a client-side implementation where I select something from another list, say:
<select name="teams">
<option value="1">Cleveland Indians</option>
<option value="2">Boston Red Sox</option>
</select>
Which then modifies the "batters" lists to a pre-defined lineup that represents that team. What's the best way to write some JS/jQuery that can see when the "teams" select changes and then modifies each value of the "batters[]" list? Is this possible using an array for the name in batters?
Hope this makes sense. Thanks!
Teams stored as a map from team name to team players:
var teams = {
'Cleveland Indians': [
{name: 'Bobby Abreu', value: 945},
{name: 'Erick Almonte', value: 808},
{name: 'Sammy Sosa', value: 999}
],
'Boston Red Sox': [
{name: 'Kurt Schilling', value: 38},
{name: 'Babe Ruth', value: 42},
{name: 'Mark McGuire', value: 101}
]
};
$('select[name=teams]').change(function ()
{
var team = teams[$(this).val()];
$('select[name="batters[]"]').html
(
$.map(team, function (elt, i)
{
return '<option value="' + elt.value + '">'
+ elt.name + '</option>';
}).join('')
);
}).change();
Demo: http://jsfiddle.net/mattball/UU99R/
Or, just an array of teams (more like the code in the OP):
var teams = [
[
{name: 'Bobby Abreu', value: 945},
{name: 'Erick Almonte', value: 808},
{name: 'Sammy Sosa', value: 999}
],
[
{name: 'Kurt Schilling', value: 38},
{name: 'Babe Ruth', value: 42},
{name: 'Mark McGuire', value: 101}
]
];
// just change
var team = teams[$(this).val()];
// to
var team = teams[this.selectedIndex];
Demo: http://jsfiddle.net/mattball/HBSU8/
You could do something like this:
$(document).ready(function(){
$("select[name='teams']").change(function(e){
var teamId = e.target.value;
console.log(e.target.value);
$.ajax({
//your url
//the data you wanna pass I suppose: teamId
//method type: GET or POST
//datatype: let's say your backend returns some JSON you would say JSON
//Finally in the successCallback you would process that JSON object and populate each of your select
});
});
});
change
<select name="batters[]">
to
<select id='batters_select' name="batters[]">
script code like:
batters[1]={{num: 443,name: "Batter Best"},{num: 443,name: "Batter Worst"}}
$(function() {
$('select:[name="teams"]').change(function() {
var me=$(this);
var options='';
var v=me.val();
for (var batter in batters[v]){
options+='<option value='+batter.num+'>'+batter.name+'</option>'
}
$('#batters_select').html(options);
}}));