I was wondering if it is possible to display a link that is associated with the option in the select field that the user selects. I am currently using a database to store the options and have a category in the database per option where "extra" information is stored. I was thinking that the extra information could be the link about the selected item. However,
I am unsure how to display this link as the user selects the item in the select field. I would also like the link to change when a different item is selected.
I am currently using Flask, Flask-WTF, Flask-sqlalchemy, HTML , and jsonify.
const fruits = {
"1": { "colour": "yellow", "shape": "long" },
"2": { "colour": "red", "shape": "round" }
};
const fruitSelect = document.getElementById('fruit');
function setFruitOptions() {
if (fruitSelect.selectedIndex !== -1) {
const fruit = fruits[fruitSelect.options[fruitSelect.selectedIndex].value];
document.getElementById('shape').textContent = fruit.shape;
document.getElementById('colour').textContent = fruit.colour;
}
}
fruitSelect.addEventListener('change', setFruitOptions);
setFruitOptions();
<select id="fruit">
<option value="1">banana</option>
<option value="2">apple</option>
</select>
is <span id="shape"></span> and <span id="colour"></span>.
You can deliver the necessary JS object in Flask using something like this in the template:
<script>
const fruits = {{ fruit_dict|tojson|safe }};
</script>
Related
Here is what I'm trying to do:
<select name="manager" id="manager" [(ngModel)]="property.manager" class="form-control" (change)="onChangeManager($event)" required>
<option disabled value="">Select Manager</option>
<option *ngFor="let manager of managers" [ngValue]="manager" [selected]="manager?.name === 'Subhan Ahmed'">
{{manager?.name}}
</option>
</select>
What I need is when the view is initialised, I need to set the value of the select where manager?.name == property.manager.name (which is loaded from db on on another event). I've tried to place a default text Subhan Ahmed to select the default value but its not working.
Managers are loaded at the start, I load them from Firestore and assign them to a variable managers: Observable<Manager>; during subscribe(), while property.manageris loaded after another input's change event.
Am i missing something?
You can select an item of the dropdown list by setting the value of property.manager. Assuming that selectedName is the name of the Manager item that you want to select, you can do this:
// Case sensitive
this.property.manager = this.managers.find(m => m.name === this.selectedName);
// Case insensitive
let selectedNameUp = this.selectedName.toUpperCase();
this.property.manager = this.managers.find(m => m.name.toUpperCase() === selectedNameUp);
Here are the relevant parts of the markup and code. See this stackblitz for a demo.
HTML:
<select name="manager" [(ngModel)]="property.manager" class="form-control" required>
<option disabled [ngValue]="undefined">Select Manager</option>
<option *ngFor="let manager of managers" [ngValue]="manager">{{manager.name}}</option>
</select>
<input type="text" [(ngModel)]="selectedName" (ngModelChange)="onNameChange($event)">
Code:
selectedName: string;
property = {
ref_no: '',
address: '',
manager: undefined
};
managers = [
{ "company": "Test Company", "name": "John Doe", "id": "3oE37Fo2QxGHw52W7UHI" },
{ "company": "Another Company", "name": "John Brown", "id": "LRF8xAi48rRuWu0KZex3" },
{ "company": "XYZ", "name": "Subhan Ahmed", "id": "TqOQHbdwJdwgwD8Oej8v" }
];
onNameChange($event) {
let selectedNameUp = this.selectedName.toUpperCase();
this.property.manager = this.managers.find(m => m.name.toUpperCase() === selectedNameUp);
}
I am making a system and I came across the following doubt .. I have two being the first to select the brand of the vehicle and the second would be to select the model of the vehicle. but I would like to select the brand of the vehicle and the of the model to load the models of the vehicles for the selected brand.
i have onde archive .json with brand and models of cars.
exemple format json
"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
<select id="brand"></select>
<select id="models"></select>
so I populate the first with the tags so the second would be populated with the models referring to the selected brand.
I need it when I select, for example BMW, the second select only the models referring to BMW, and not all models.
How do you do this?
thanks :)
I don't know enough about how the data is being fetched, but I believe you're asking about manipulating it in a way that makes it usable by the 2 selects. Take a look at the example below:
var json = [{
"value": "ACURA",
"title": "Acura",
"models": [{
"value": "CL_MODELS",
"title": "CL Models (4)"
}]
},
{
"value": "TOYOTA",
"title": "Toyota",
"models": [{
"value": "TOYOTA_MODELS",
"title": "Toyota Models (4)"
}]
}
];
$(document).ready(function() {
$('#models').prop('disabled', true);
$('#brand')
.append($("<option></option>")
.attr("value", "")
.text(""));
$.each(json, function(index) {
$('#brand')
.append($("<option></option>")
.attr("value", json[index]["value"])
.text(json[index]["title"]));
});
$('#brand').change(function() {
process($(this).children(":selected").html());
});
});
function process(brand) {
$('#models').prop('disabled', false).find('option')
.remove()
.end();
var models = $.map(json, function(entry) {
if (entry["title"] === brand) {
return entry["models"];
}
});
$.each(models, function(index) {
$('#models')
.append($("<option></option>")
.attr("value", models[index]["value"])
.text(models[index]["title"]));
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
//YOUR_JSON_DATA
//{"value":"ACURA","title":"Acura","models":[{"value":"CL_MODELS","title":"CL Models (4)"}]}
$.get( YOUR_JSON_DATA, function( data ) {
// Did you want data to be an array of brands?
for (let brand of data) {
$("#brand").append(`<option>${ brand.value }</option>`)
for (let models of brand.models) {
$("#models").append(`<option> ${ models.value } </option>`)
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="brand"></select>
<select id="models"></select>
Here is an example code snippet for ya. I hope it provides some clarity. Did you want the JSON data be an array?
I have two dropdown menus in my angular app. When I select an option in the 1st dropdown menu, I want that choice to effect the 2nd dropdown menu. Example: 1st menu will have a list of status messages. When I select, let's say, "Need Maintenance" It will change the 2nd menu to the departments relevant to the Maintenance. Or if I choose the status "Lost", it will change the 2nd menu to the departments relevant to the Lost status. Here is my code and setup:
.controller('HomeCtrl', function($scope, $rootScope, $http, $ionicPlatform) {
// This disables the user from being able to go back to the previous view
$ionicPlatform.registerBackButtonAction(function (event) {
event.preventDefault();
}, 100);
// This function only gets called when the submit button is hit on the messaging screen. It posts to server for sending of message
$scope.submit = function() {
$http.post('http://localhost:8000/', {
messageText: $scope.messageText,
name: window.localStorage.getItem("username")
});
$scope.messageText = ""; //clearing the message box
}
})
<div class="form1" ng-controller="HomeCtrl">
<form class="form">
<select placeholder="Select a Subject" ng-model="selectSubject" data-ng-options="option.subject for option in subject"></select>
<select placeholder="Select a Department" ng-model="selectDept" data-ng-options="option.dept for option in dept"></select>
<input type="text" class="messageText" placeholder="Message" ng-model="messageText">
<button class="button" ng-click="submit()"><span>Submit</span></button>
</form>
</div>
That is my controller relevant to the html that is also posted.
I know how to get the information I need from my node server which will be housing the information. All I need help figuring out is changing the options within the 2nd menu when a option is clicked in the 1st menu.
I am thinking just having a http.get call when a option is clicked which will then populate the 2nd menu. The first menu will be static, not changing.
I've just started messing around with Angular and a database and and was able to dynamically populate one select based on the choice in another.
Below is the HTML for my two select boxes (my second select is a multiple, but you can obviously remove that attribute):
<label>Select a Table</label>
<select name="tableDropDown" id="tableDropDown"
ng-options="table.name for table in data.availableTables"
ng-model="data.selectedTable"
ng-change="getTableColumns()">
</select>
<label>Select Columns</label>
<select name="columnMultiple" id="columnMultiple"
ng-options="column.name for column in data.availableColumns"
ng-model="data.selectedColumns"
multiple>
</select>
And I have the controller below. The init function clears all of the data sources for the two select's, retrieves the list of tables (for the first select), sets the selected table to the first table in the list, and then calls the second function.
The second function (which is also called whenever the selected table changes, thanks to the ng-change directive) retrieves the metadata for the selected table and uses it to populate the second select with the list of available columns.
.controller('SimpleController', function($scope, $http) {
init();
function init() {
$scope.data = {
availableTables: [],
availableColumns: [],
selectedTable: {}
};
$http.get("http://some.server.address")
.then(function (response) {
$scope.data.availableTables = response.data.value;
$scope.data.selectedTable = $scope.data.availableTables[0];
$scope.getTableColumns();
});
}
$scope.getTableColumns = function () {
$scope.data.selectedColumns = [];
table = $scope.data.selectedTable.url;
if (table != "") {
$http.get("http://some.server.address/" + table + "/$metadata?#json")
.then(function (response) {
$scope.data.availableColumns = response.data.value;
});
}
}
...
});
maybe you can use the ng-change directive on the 1st select and using the callback function to populate the 2nd select in the way you prefer( http call or local data).
if your Departments objects has a references to the Subject object, something like a subject_id, you can just do a filter:
Example:
<div ng-controller="MyCtrl">
subjects
<select placeholder="Select a Subject" ng-model="selectSubject" ng-options="subject.name for subject in subjects"></select>
departmets
<select placeholder="Select a Department" ng-model="selectDept" ng-options="dept.name for dept in depts | filter:{ subject_id : selectSubject.id }"></select>
</div>
var myApp = angular.module('myApp',[]);
function MyCtrl($scope) {
$scope.subjects = [
{
id: 1,
name: "sub 1",
},
{
id: 2,
name: "sub 2",
}
];
$scope.depts = [
{
id: 1,
name: "Dep 1",
subject_id: 1
},
{
id: 2,
name: "Dep 2",
subject_id: 1
},
{
id: 3,
name: "Dep 3",
subject_id: 2
},
{
id: 4,
name: "Dep 4",
subject_id: 2
}
]
}
I know there's been a lot of questions for this but I am having the most annoying time figuring out how AngularJS handles select option values and which one is selected. I have a simple item which I pass onto a modal window. This item contains template_id. I also have templates which have a name and an id and I wish to create a simple select where the option which has the value of the item's template_id gets selected:
<select name="templateId">
<option value="8000">name</option>
<option value="8001" selected>name 2</option>
</select>
Now with AngularJS I do this:
<select name="templateId"
ng-model="domain.templateId"
ng-options="t.template_id as t.name for t
in templates track by t.template_id">
<option value="">Choose template</option>
</select>
In the controller I set the 'selected' value with:
Data.get('templates').then(function(result) {
$scope.templates = result;
});
$scope.domain = {
template_id: item.template_id,
templateId: { template_id: item.template_id }
};
I have actually gotten to a point where I can send the template_id to the REST API and the response there reads
template_id: 8000
However, there is some minor annoying behaviour in the select element. I get the item I want selected, but when I attempt to select another option it switches the selected to the pre-set 'Choose template' option but the value or rather the 'real selected item' is still the original "selected" value I set in the controller. I can see it in the REST API response. This is not however what I selected. After this initial bug it continues to work as it's supposed to but how can I get rid of this?
Here a example to solve your issue.
angular.module('app.select', [])
.controller('SelecetCtrl', function($scope) {
$scope.templates = [{
template_id: 1,
name: 'tst1'
}, {
template_id: 2,
name: 'tst2'
}, {
template_id: 3,
name: 'tst3'
}];
$scope.selected = {
template: {
template_id: 2
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app='app.select'>
<div ng-controller='SelecetCtrl'>
<select name="templateId" ng-model="selected.template"
ng-options="t as t.name for t
in templates track by t.template_id">
<option value="">Choose template</option>
</select>
</div>
</div>
i am seeing the example here https://docs.angularjs.org/api/ng/directive/select and this have 3 select with the same value, how can i have different values selected in my options?
i have this:
<li ng-repeat="tarea in tareas">
<input type="checkbox" ng-model="tarea.COMPLETADA" ng-change="updTarea(tarea.ID)"/>
<span class="done-{{tarea.COMPLETADA}}" >{{tarea.NAME}} {{tarea.CLASIFICADORES}}</span>
<select ng-model="selectedOpt"
ng-options="clasificador.NAME for clasificador in clasificadores">
</select>
<button class="buttons delete right" ng-click="delTarea(tarea.ID)"> Eliminar</button>
</li>
so i can have 5,10,15 options, and i want to make a selected item with the value that i have in tarea.CLASIFICADORES, i tried with this
$scope.selectedOpt = $scope.clasificadores[1]
but that make all the options with the same value, like in the example...
how can i make different selected item in my options dynamically with a value i have in my ng-repeat in every item?
i load the data with ajax...
my problem is to set the default selected item with the tarea.CLASIFICADORES. for example, i have a todo list that have a classifier, i want my ng-options to select by default my database value clasifier when the page is load
The problem is, that you are using the same scope variable for all selections. You could store the selected options in an array too like this:
function TestCtrl($scope) {
$scope.items = [
{ id: 1, class: 1 },
{ id: 2, class: 2 },
{ id: 3, class: 1 },
];
$scope.classes = [
{ name: "class 1", id: 1},
{ name: "class 2", id: 2},
{ name: "class 3", id: 3}
];
};
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app>
<div ng-controller="TestCtrl">
<div ng-repeat="currentItem in items">
<select ng-model="selectedClass[$index]" ng-init="selectedClass[$index]=(classes|filter:{id: currentItem.class})[0]" ng-options="class.name for class in classes track by class.id" >
</select>
selected class: {{selectedClass[$index]}}
</div>
</div>
</div>
In this example I take use of the variable $index, which is set by the ng-repeat directive. As the name suggests it contains the current index of the repeat-loop.
UPDATE
I updated the code-snippet so it sets the default value for each select input.
The different items now contain a field with the id of the corresponding class. I initialize the select input with ng-init. With this directive I set selectedClass[$index] which is the selected value for the current item. As we only have the class-id as a property of the items I use a filter to find the corresponding class object with the id (classes|filter:{id: currentItem.class})[0]
To get rid of the filter you could just set the class of each item to the full class-object instead of the id.