Three dimensional Javascript array - javascript

I am trying to build a 3D Javascript array, but I am unsure of how to do it, basically I have 3 arrays, Provinces, Cities and Malls all in succession, so I want to create a 3D array to store all the data in and then write some jQuery/Javascript to get out what I need.
I have a script that can populate a drop down list with array items, but now I am adding an extra dimension to it and I am getting a little confused as to how to proceed, here is the code I have thus far,
The jQuery:
<script>
model[0] = new Array( 'Arnage', 'Azure', 'Brooklands', 'Continental', 'Corniche', 'Eight', 'Mulsanne', 'Series II', 'Turbo R', 'Turbo RT');
model[1] = new Array( '412', '603', 'Beaufighter', 'Blenheim', 'Brigand', 'Britannia');
model[2] = new Array( 'Inyathi', 'Rhino');
model[3] = new Array( 'Amandla', 'Auto Union', 'Horch');
function makeModel(obj){
var curSel=obj.options[obj.selectedIndex].value ;
var x;
if (curSel != 'null'){
$('#model').css({'display' : 'block'});
$('#model').html("<select name='model' id='sub'>");
for (x in model[curSel])
{
$('#sub').append("<option value='" + model[curSel][x] + "'>" + model[curSel][x] + "</option>");
}
}else{
$('#model').css({'display' : 'block'});
}
}
</script>
The HTML:
<form>
<p>
<span class='left'><label for='make'>Make: </label></span>
<span class='right'><select name='make' id='make' onchange='makeModel(this);'>
<option value='0'>Select one</option>
<option value='1'>one</option>
<option value='2'>two</option>
<option value='3'>three</option>
<option value='4'>four</option>
</select>
</span>
</p>
<p>
<div id='model'></div>
</p>
</form>
So as you can see, the above code generates a drop down menu of models depending on what make I select, now what I want to achieve now is adding one more level to it, so they will click on a province, then the cities drop down will appear, and when they choose a city, the malls will appear.
What would be the best way of approaching this?
Thanx in advance!

If you have a structure like this one
var provinces = [
{ name: "Province A", cities: [
{ name: "City A.A", malls: [
{ name: "Mall A.A.1" },
{ name: "Mall A.A.2" }
] },
{ name: "City A.B", malls: [
{ name: "Mall A.B.1" }
] }
] },
{ name: "Province B", cities: [
{ name: "City B.A", malls: [
{ name: "Mall B.A.1" },
{ name: "Mall B.A.2" }
] },
{ name: "City B.B", malls: [] }
] }
];
Then you can populate the dropdowns like so:
function populateDropdown(drop, items) {
drop.empty();
for(var i = 0; i < items.length; i++) {
drop.append('<option value=' + i + '>' + items[i].name + '</option>');
}
drop.show();
}
populateDropdown( $('#provinces'), provinces );
And upon an action:
$('#provinces').change(function() {
var provinceIndex = $(this).val();
var province = provinces[provinceIndex];
populateDropdown( $('#cities'), province.cities );
$('#malls').hide();
});
$('#cities').change(function() {
var provinceIndex = $('#provinces').val();
var province = provinces[provinceIndex];
var cityIndex = $(this).val();
var city = province.cities[cityIndex];
populateDropdown( $('#malls'), city.malls );
});
EDIT
If the data structure on top looks hard to read, by the way, it's the exact same thing as the following:
var provinces = [];
// populate provinces
provinces.push({ name: "Province A", cities: [] });
provinces.push({ name: "Province B", cities: [] });
// populate cities
provinces[0].cities.push({ name: "City A.A", malls: [] });
provinces[0].cities.push({ name: "City A.B", malls: [] });
provinces[1].cities.push({ name: "City B.A", malls: [] });
provinces[1].cities.push({ name: "City B.B", malls: [] });
// populate malls
provinces[0].cities[0].malls.push({ name: "Mall A.A.1" });
provinces[0].cities[0].malls.push({ name: "Mall A.A.2" });
provinces[0].cities[1].malls.push({ name: "Mall A.B.1" });
provinces[1].cities[0].malls.push({ name: "Mall B.A.1" });
provinces[1].cities[0].malls.push({ name: "Mall B.A.2" });

Related

How to make a group of same values

I have a simply array and want to loop through the array which have some same key and value, and i want to make a group of those values which are the same and put the related item under that.
export class AppComponent implements OnInit {
data = [
{
'con': 'Usa',
'city': 'ny',
'town':'as'
},
{
'con': 'Ger',
'city': 'ber',
'town':'zd'
},
{
'con': 'Usa',
'city': 'la',
'town':'ss'
}
];
array: any[] = [];
ngOnInit() {
this.array = this.data;
}
}
html:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<p>{{item.city}}</p>
<p>{{item.town}}</p>
<hr>
</div>
and i have a following result:
Usa
ny
as
-----
Ger
ber
zd
-----
Usa
la
ss
-----
but what i really wants is to make a group of those country with the same name and display the related cities and town under that with the following format:
[{
"con": "usa",
"area": [{
"city": "ny",
"town": "as"
}, {
"city": "la",
"town": "ss"
}]
},
{
"con": "ger",
"area": [{
"city": "ber",
"town": "zd"
}]
}
]
Transform the data to an array with the consolidated objects, where the cities properties have arrays, like so
[
{ con: "Usa": cities: ["ny", "la"] },
{ con: "Ger", cities: ["ber"] }
]
You can build that data structure as follows:
this.array = Array.from(
this.data.reduce(
(map, {con, city}) => map.set(con, (map.get(con) || []).concat(city)),
new Map
), ([con, cities]) => ({ con, cities })
);
Then the HTML part becomes:
<div *ngFor="let item of array ">
<h3>{{item.con}}</h3>
<div *ngFor="let city of item.cities ">
<p>{{city}}</p>
</div>
<hr>
</div>
You can sort your JSON before passing to angular ngFor as bellow,
data = [
{
'con': 'Usa',
'city': 'ny'
},
{
'con': 'Ger',
'city': 'ber'
},
{
'con': 'Usa',
'city': 'la'
}
];
var expectedResult = data.sort(function (a, b) {
return a.con.localeCompare(b.con);
});
console.log(expectedResult)
//OR
// change order as return b.con.localeCompare(a.con);

How to get a certain data in the second autocomplete input that depend on what typed in the first input in React.js?

Okay, so I don't know how to properly express my simple problem because of how simple it is, I guess.
Basically, I have an autocomplete done by me in my React project.. I have two inputs "Country" and "City". When I type a country my autocomplete works great giving me suggestions but now I have to make the same for my second input so it would give me a list of cities that depends on which country is typed in the "Country" input...
"United Kingdom" => "London, Birmingham, Bighton etc."
How can I do that? Thank you!
P.S. I already have all the lists of countries and cities, I just don't know how to make the second input to depend on an information in the first one.
Code here
Autocomplete.jsx
https://github.com/lembas-cracker/Weather-app/blob/master/src/Autocomplete.jsx
Form.jsx
https://github.com/lembas-cracker/Weather-app/blob/master/src/Form.jsx
P.S. I already have all the lists of countries and cities, I just don't know how to make the second input to depend on an information in the first one.
If you know which country the city belongs to (perhaps via a key in the city object), you could run a simple filter function to remove any cities that don't belong to that country.
this.state = {
selectedCountry: 'London',
};
const cities = [
{ name: "Toronto", country: "Canada" },
{ name: "London", country: "United Kingdom" }
];
const filteredCities = cities.filter(city => {
return city.country !== this.state.selectedCountry;
});
On your city input field make sure to create an onBlur function to will run the filter on your cities list once the user leaves that input field.
Made a quick example. Did you mean smth like this? Since you haven't provided any part of your source code, I used plain HTML select for the demo.
https://jsfiddle.net/arfeo/n5u2wwjg/204186/
class App extends React.Component {
constructor() {
super();
this.state = {
countryId: 1,
};
}
onCountryChange(countryId) {
this.setState({ countryId: parseInt(countryId) });
}
render() {
return (
<div>
<Input
key="countriesInput"
type="countries"
countryId={this.state.countryId}
onChange={(countryId) => this.onCountryChange(countryId)}
/>
<Input
key="citiesInput"
type="cities"
countryId={this.state.countryId}
/>
</div>
);
}
}
class Input extends React.Component {
constructor() {
super();
this.selectRef = null;
}
renderOptions() {
const countries = [
{
id: 1,
name: 'England',
},
{
id: 2,
name: 'Germany',
},
{
id: 3,
name: 'France',
},
];
const cities = [
{
countryId: 1,
cities: [
{
id: 1,
name: 'London',
},
{
id: 2,
name: 'Liverpool',
},
{
id: 3,
name: 'Salisbury'
}
],
},
{
countryId: 2,
cities: [
{
id: 4,
name: 'Berlin',
},
{
id: 5,
name: 'Frankfurt',
},
],
},
{
countryId: 3,
cities: [
{
id: 6,
name: 'Paris',
},
],
},
];
switch (this.props.type) {
case 'countries': {
return countries.map((country) => (
<option
key={country.id.toString()}
value={country.id}
>
{country.name}
</option>
));
}
case 'cities': {
const citiesMap = cities.filter((city) => city.countryId === this.props.countryId);
if (citiesMap && citiesMap[0]) {
const citiesList = citiesMap[0].cities;
if (citiesList) {
return citiesList.map((city) => (
<option
key={city.id.toString()}
value={city.id}
>
{city.name}
</option>
));
}
}
return null;
}
default: return null;
}
}
render() {
return (
<select name={this.props.type} ref={(ref) => this.selectRef = ref} onChange={() => this.props.onChange(this.selectRef.value)}>
{this.renderOptions()}
</select>
);
}
}
ReactDOM.render(<App />, document.querySelector("#app"))
UPDATE
Make your Form component stateful.
Add a state property for countries in Form (let it be countryId).
Pass this property as a prop into the second Autocomplete component.
When the first Autocomplete changes, change the countryId of the Form.
I've done something similar which may help you.
The Object.keys(instutiontypes) you could use to have an array of countries, instead. Then inside of those values, you can have an array of objects. You could have the cities here, e.g. {value: "Manchester", "label: Manchester", phoneExt: "0114"}
const instutiontypes = {
Kindergarten: [
{ value: "PreK", label: "PreK" },
{ value: "K1", label: "K1" },
{ value: "K2", label: "K2" },
{ value: "K3", label: "K3" },
],
"Primary School": [
{ value: "Grade 1", label: "Grade 1" },
{ value: "Grade 2", label: "Grade 2" },
{ value: "Grade 3", label: "Grade 3" },
{ value: "Grade 4", label: "Grade 4" },
{ value: "Grade 5", label: "Grade 5" },
{ value: "Grade 6", label: "Grade 6" },
],
}
To have the options in my input, I use Object.keys(instutiontypes) to get ['Kindergarten','Primary School']
Then, to get the array of ages to give to my secondary dropdown, I have written this code:
const types = ['Selection1', 'Selection2']
const agesList = [];
for (let i = 0; i < types.length; i++) {
Object.values(institutionTypes[types[i]]).map(({ label }) =>
agesList.push(label)
);
}
This way, the ages dropdown list is dependent on the values passed to institutionTypes.
I'm using mui's <Autocomplete /> components to make them be search dropdowns, with the prop options for the arrays.

How to filter the values based on selection using jquery?

I have two drop downs one for movies and another for theaters when i select the movie in first drop down to print the selected movie and which theater the movie is playing and same as select the theater to print the theater and which movie playing that theater ?
how to do that one ....
$(document).ready(function() {
var cityData = [{
cityName: 'Bengaluru',
value: "Bengaluru",
data: [{
movieName: 'ABC',
theaterName: 'Tulsi Theatre'
},
{
movieName: 'DEF',
theaterName: 'PVR'
},
{
movieName: 'GHI',
theaterName: 'Srinivasa Theatre'
}
]
},
{
cityName: 'Hyderabad',
value: "Hyderabad",
data: [{
movieName: '123',
theaterName: 'Theatre1'
},
{
movieName: '456',
theaterName: 'PVR2'
},
{
movieName: '789',
theaterName: 'Theatre3'
}
]
},
{
cityName: 'Guntur',
value: "Guntur",
data: [{
movieName: 'ABC1',
theaterName: 'Theatre4'
},
{
movieName: 'DEF2',
theaterName: 'PVR3'
},
{
movieName: 'GHI3',
theaterName: 'Theatre5'
}
]
},
{
cityName: 'Ongole',
value: "Ongole",
data: []
}
];
$("#selectCity").on('change', function() {
var locations = cityData.filter(c => c.cityName === $(this).val())[0].data;
var locationString = '';
var locationString2 = '';
$.each(locations, function(i, item) {
locationString += '<option value="' + item.theaterName + '">' + item.theaterName + '</option>';
locationString2 += '<option value="' + item.movieName + '">' + item.movieName + '</option>';
});
$('#secondselectbox').html(locationString);
$('#thirdselectbox').html(locationString2);
});
$("#thirdselectbox, #secondselectbox, #selectCity").on("change", function() {
$("span#selectedMovie").text($("#thirdselectbox").val());
$("span#selectedTheater").text($("#secondselectbox").val());
});
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="UserData">
<h1>Booking</h1>
<select class="selectCity" id="selectCity">
<option value="City">Select City</option>
<option value="Bengaluru">Bengaluru</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Guntur">Guntur</option>
<option value="Ongole">Ongole</option>
</select>
<span id="welcome"> </span>
<select class="selectTheater" id="secondselectbox">
</select>
<select class="selectMovie" id="thirdselectbox">
</select>
</div>
<fieldset style="margin-top:20px;">
<legend>Your Selection</legend>
<div>Theater: <span id="selectedTheater"></span></div>
<div>Movie: <span id="selectedMovie"></span></div>
</fieldset>
how to filter the values based on selection
when i am selecting the movie to print the movie name and which theater the movie is playing as same as selection of theater.
and how to store the selected values in local storage.
Lets Solve the problem step by step
Note: I will use your code , I won't invent my own
first : we will make one change method for every select element to make our code better like this
// city selection
$('#selectCity').on('change', function() {});
// theater selection
$('#secondselectbox').on('change', function() {});
// Movie selection
$('#thirdselectbox').on('change', function() {});
second: we will make the locations variable global so that we can track the current selected data in the other methods so on top of the methods above we make this change
var locations = [] ;
third : we have a small error happens when when we select a city then we select the option Select City we get the error
can read data of undefined
so to solve it we just need to check that the user does not select the select city option like this .
$('#selectCity').on('change', function() {
if ( $(this).val().indexOf('City') === -1) {
// here our logic
}
});
finally : when the user select a movie or a theater we go all the elements of our locations and check if the current element has the movie or the theater we selected and based on that we change our data
Here is the full code for the solution I wrote so comments some you understand it if you have anything you don't understand I am here to help .
Hope this helps you
$(document).ready(function() {
var cityData = [
{
cityName: 'Bengaluru',
value: 'Bengaluru',
data: [
{
movieName: 'ABC',
theaterName: 'Tulsi Theatre',
},
{
movieName: 'DEF',
theaterName: 'PVR',
},
{
movieName: 'GHI',
theaterName: 'Srinivasa Theatre',
},
],
},
{
cityName: 'Hyderabad',
value: 'Hyderabad',
data: [
{
movieName: '123',
theaterName: 'Theatre1',
},
{
movieName: '456',
theaterName: 'PVR2',
},
{
movieName: '789',
theaterName: 'Theatre3',
},
],
},
{
cityName: 'Guntur',
value: 'Guntur',
data: [
{
movieName: 'ABC1',
theaterName: 'Theatre4',
},
{
movieName: 'DEF2',
theaterName: 'PVR3',
},
{
movieName: 'GHI3',
theaterName: 'Theatre5',
},
],
},
{
cityName: 'Ongole',
value: 'Ongole',
data: [],
},
];
// make locations global to track it
var locations = [] ;
$('#selectCity').on('change', function() {
if (
$(this)
.val()
.indexOf('City') === -1
) {
locations = cityData.filter(
c => c.cityName === $(this).val(),
)[0].data;
var locationString = '';
var locationString2 = '';
$.each(locations, function(i, item) {
locationString +=
'<option value="' +
item.theaterName +
'">' +
item.theaterName +
'</option>';
locationString2 +=
'<option value="' +
item.movieName +
'">' +
item.movieName +
'</option>';
});
$('#secondselectbox').html(locationString);
$('#thirdselectbox').html(locationString2);
// here we change the values of the current movie and theater
$('span#selectedMovie').text($('#thirdselectbox').val());
$('span#selectedTheater').text($('#secondselectbox').val());
}
});
$('#secondselectbox').on('change', function() {
// here the theater change
// get the selected value
var theater = $(this).val();
// here we need to go through every element in locations
for(var i in locations){
// checks if the current element
// check if its theater equal current theater
// chenage the values
if(locations[i].theaterName===theater){
// here we change the data
$('span#selectedTheater').text(theater);
$('span#selectedMovie').text(locations[i].movieName);
$('#thirdselectbox').val(locations[i].movieName);
}
}
});
$('#thirdselectbox').on('change', function() {
// here the movie change
// get the selected value
var movie = $(this).val();
// here we need to go through every element in locations
for(var i in locations){
// checks if the current element
// check if its movie equal current movie
// chenage the values
if(locations[i].movieName===movie){
// here we change the data
$('span#selectedMovie').text(movie);
$('span#selectedTheater').text(locations[i].theaterName);
// also we need the change the selection value
$('#secondselectbox').val(locations[i].theaterName);
}
}
});
});
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<div class="UserData">
<h1>Booking</h1>
<select class="selectCity" id="selectCity">
<option value="City">Select City</option>
<option value="Bengaluru">Bengaluru</option>
<option value="Hyderabad">Hyderabad</option>
<option value="Guntur">Guntur</option>
<option value="Ongole">Ongole</option>
</select>
<span id="welcome"> </span>
<select class="selectTheater" id="secondselectbox">
</select>
<select class="selectMovie" id="thirdselectbox">
</select>
</div>
<fieldset style="margin-top:20px;">
<legend>Your Selection</legend>
<div>Theater: <span id="selectedTheater"></span></div>
<div>Movie: <span id="selectedMovie"></span></div>
</fieldset>
Track your control's onchange event. Then do the second process.
Example:
$("#dropdownId").on('change', function() {
//do the necessary process here
});

Pagination with filters using ng-repeat in angular

I am trying to do a pagination using filters.
There is a list with names and countries.
I am trying to filter them by country and also alphabetical range, and then generate the pagination by numbers. I am really stuck with it. any help will be really appreciate it
The alphabetical filter will retrieve the names that start with the the range of letters. For example if you select the first option [A - M] will return the person that their name start within that range of letters
Here is my code. The html is over there. Thanks
http://jsbin.com/cifowatuzu/edit?html,js,output
angular.module('app',['angular.filter'])
.controller('MainController', function($scope) {
$scope.selectedCountry = '';
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
//This should store {StartFrom and To from selected Range}
$scope.selectedRange = '';
$scope.AlphabethicalRange = [
{StartFrom: 'A', To: 'M'},
{StartFrom: 'N', To: 'Z'}
];
$scope.Countries = [
{ Name : 'USA'},
{ Name : 'Japan'},
{ Name : 'France'},
{ Name : 'Canada'},
{ Name : 'China'},
];
$scope.People = [
{ Id: 1, Name: 'Will', Country: 'USA'},
{ Id: 2, Name: 'Ed', Country: 'USA' },
{ Id: 3, Name: 'Peter', Country: 'China'},
{ Id: 4, Name: 'John', Country: 'Japan'},
{ Id: 5, Name: 'Alex', Country: 'France'},
{ Id: 6, Name: 'Jim', Country: 'France'},
{ Id: 7, Name: 'Austin', Country: 'Italy'},
{ Id: 8, Name: 'Men', Country: 'France'},
{ Id: 9, Name: 'Zike', Country: 'Canada'},
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function () {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
I create a custom filter to filter the range that you want.
Here's a snippet working:
var app = angular.module('app', ['angular.filter']);
app.controller('mainCtrl', function ($scope) {
$scope.currentPage = 1;
$scope.pageSize = 3;
$scope.pages = [];
$scope.AlphabethicalRange = [
{
"StartFrom":"A",
"To":"M"
},
{
"StartFrom":"N",
"To":"Z"
}
];
$scope.Countries = [
{
"Name":"USA"
},
{
"Name":"Japan"
},
{
"Name":"France"
},
{
"Name":"Canada"
},
{
"Name":"China"
}
];
$scope.People = [
{
"Id":1,
"Name":"Will",
"Country":"USA"
},
{
"Id":2,
"Name":"Ed",
"Country":"USA"
},
{
"Id":3,
"Name":"Peter",
"Country":"China"
},
{
"Id":4,
"Name":"John",
"Country":"Japan"
},
{
"Id":5,
"Name":"Alex",
"Country":"France"
},
{
"Id":6,
"Name":"Jim",
"Country":"France"
},
{
"Id":7,
"Name":"Austin",
"Country":"Italy"
},
{
"Id":8,
"Name":"Men",
"Country":"France"
},
{
"Id":9,
"Name":"Zike",
"Country":"Canada"
}
];
$scope.numberPages = Math.ceil($scope.People.length / $scope.pageSize);
$scope.init = function() {
for (i = 1; i < $scope.numberPages; i++) {
$scope.pages.push(i);
}
};
$scope.init();
});
app.filter('rangeAlphaFilter', function() {
return function(items, search) {
if (!search || search == ' - ') {
return items;
}
return items.filter(function(element) {
return new RegExp('[' + search.replace(/ /g, '') + ']', 'i').test(element.Name[0]);
});
}
});
<!DOCTYPE html>
<html ng-app="app">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.7/angular.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-filter/0.5.8/angular-filter.min.js"></script>
</head>
<body ng-controller="mainCtrl">
<div>
<span>Country Filter</span>
<select name="countriesSelect" ng-options="c as c.Name for c in Countries" ng-model="selectedCountry">
<option value="">-- Select a country --</option>
</select>
<br>
<span>Alphabetical Filter</span>
<select name="AlphabeticalSelect" ng-options="a as a.StartFrom +' - '+ a.To for a in AlphabethicalRange" ng-model="selectedRange">
<option value="">-- Select a range --</option>
</select>
<ul>
<li ng-repeat="person in People | filter: { Country: selectedCountry.Name } | rangeAlphaFilter: selectedRange.StartFrom +' - '+ selectedRange.To" ng-bind="person.Name"></li>
</ul>
<span>Pagination Numbers</span>
{{page}}
</div>
</body>
</html>
PS: To control the pagination, I extremely don't recommend you to do it manually, it gives a lot of work. I recommend you to see my answer in this another question, it's like a "mini" tutorial of how to use the angularUtils-pagination. Check it.
I hope it helps.

Using JS/jQuery to manipulate option select list where the name is an array

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);
}}));

Categories