Hi I'm nearly finished with my small task of populating select dropdowns then outputting a relevant number. The select a company etc works.
Here's my JSFiddle: http://jsfiddle.net/3MK3D/1/
I need to now generate the appropriate companies in the select dropdown dependent on which sector is selected. I've created a new javascript array for personal companies.
I've thought of maybe doing something like this and passing the correct variable to the appropriate function but not really sure how to implement it:
var companiesArray;
$('#sector').on('change', function(e){
var optionSelected = $("option:selected", this);
var sectorSelected = this.value;
if( sectorSelected == 'business' ) {
companiesArray = 'insurancecompanies';
} else if( sectorSelected == 'personal' ) {
companiesArray = 'personalcompanies';
} else {
}
});
There is probably a better way?
Use a companies object that has your sector select values as keys to the relevant arrays:
var companies = {
business : [
{
name : 'Advent',
property : '01242 674 674',
fleet : '',
motortrade : ''
},
{
name : 'Allianz',
property : '0844 412 9988',
fleet : '0800 587 5858',
motortrade : ''
},
// other insurance companies
],
personal : [
// personal companies
]
}
Then:
$('#sector').on('change', function(e){
var optionSelected = $("option:selected", this);
var sectorSelected = this.value;
var companyArray = companies[sectorSelected];
// iterate over companyArray and create the relevant option objects for #company
});
Related
I want just to get only country code with plus in html input, this intl-tel-input now working, that showing specific country code number example. I don`t want this , what i need is just to show automatically iti__dial-code (country code) .
How can i solve this issue ?
var input = document.querySelector("#phone");
intlTelInput(input, {
customPlaceholder: function(selectedCountryPlaceholder, selectedCountryData) {
return "(201) 555-0123" ;
},
});
window.intlTelInput(input, {
initialCountry:"auto",
geoIpLookup: function(success, failure){
$.get("https://ipinfo.io", function() {}, "jsonp").always(function(resp) {
var countryCode = ('+' && resp && resp.country) ? resp.country : "";
success(countryCode);
});
},
dropdownContainer: document.body,
utilsScript: "Project A_files/utils.js",
});
You need to get instance of input and then get it's country data.
var iti = window.intlTelInputGlobals.getInstance(input);
var countryData = iti.getSelectedCountryData();
Country data will return something like:
{
name: "Afghanistan (افغانستان)",
iso2: "af",
dialCode: "93"
}
Get the dialcode by:
var dialCode = countryData["dialCode"];
Refered from the official documentation of the library at https://github.com/jackocnr/intl-tel-input
I have a page that I create using JS from API data.
I would like to filter the data based on two filter options: Location and Department.
I could do this pretty easily if it were just one filter option selected at any given time but sense any combination of filter options can be selected at any one time, i'm pretty lost.
So far my JS function to create each item on the page looks as such:
function createOffer(job){
var $div = $('<div>', {'class': 'job-listing'});
var $divDetails = $('<div>', {'class': 'job-listing__details'});
var $title = $('<h2>'+job.title+'</h2>').addClass('job-listing__title');
var $location = $('<span data-type="location" data-location="'+job.city+','+job.state+'">Location: </span>').addClass('job-listing__detail location');
var $department = $('<span data-type="department" data-department="'+job.department+'">Department: </span>').addClass('job-listing__detail job-listing__detail--department department');
var $viewMoreBtn = $('<a>+View Details</a>').addClass('job-listings__view-more');
var $divViewMore = $('<div>', {'class': 'job-listing__more'});
if(!allLocations.includes(job.city+','+job.state)){
allLocations.push(job.city+','+job.state);
}
if(!allDepartments.includes(job.department)){
allDepartments.push(job.department);
}
$div.append($title);
$divDetails.append($location);
$divDetails.append(''+job.city+','+job.state);
$divDetails.append($department);
$divDetails.append(''+job.department);
$divViewMore.append(job.description);
$div.append($divDetails);
$div.append($divViewMore);
$div.append($viewMoreBtn);
allJobs.push($div);
$jobsContainer.append($div);
}
How would I go about filtering with two filter options all being able to select multiple filter options at any given time?
Could be something like that:
const $jobLocationFilter = $('#jobLocationFilter').val(); // Pretend it's a text field
const $jobDepartmentFilter = $('#jobDepartmentFilter ').val(); // Pretend it's a text field
const jobsFiltered = jobListFromDatabase.filter(job =>
// If job location filter has value, filter by it, else includes this job (returns true)
( $jobLocationFilter ? job.location === $jobLocationFilter : true )
&&
// If job dep. filter has value, filter by it, summing with the previous filter
( $jobDepartmentFilter ? job.department === $jobDepartmentFilter : true )
/*
And this could go on with multiple filters,
just adding && and another expression to filter. e.g:
`
( $jobMinSalaryFilter ? job.salary >= $jobMinSalaryFilter : true )
&&
... others
`
*/
);
// Function to render the filtered jobs
renderJobs(jobsFiltered);
I am trying to display a result det data on a table and a chart together. For exampIe: A user gives a value as an input and a query has to be made to the server to filter the table based on the user input and give nbacj the result set.
I am implementing a filter on the table and then bind the filtered result set to the table. I write the below code which works fine.
var oModel = new sap.ui.model.odata.ODataModel( "../TEST_ODATA.xsodata",false);
oTable.setModel(oModel);
var oFilter=new sap.ui.model.Filter("SUPPLIERID",sap.ui.model.FilterOperator.EQ,oInput1.getValue());
oTable.getBinding("rows").filter(oFilter);
var NumberOfRows = oTable.getBinding("rows").iLength;
oTable.setTitle("Title1" + "(" + NumberOfRows + ")");
oTable.placeAt("content");
Now I need to bind ofilter to a chart too and I write the following code which does not work.
var oDataset = new sap.viz.ui5.data.FlattenedDataset({
dimensions : [{axis : 1, name : 'SUPPLIERID', value : "{SUPPLIERID}"},{axis : 2, name : 'MATERIALNUMBER', value : "{MATERIALNUMBER}"}],
measures : [{name : 'Result', value : '{Result}'}],
data : {
path : "/service_path"
}});
var oStackChart = new sap.viz.ui5.StackedColumn({
width : "80%",
height : "400px",
plotArea : {'colorPalette' : d3.scale.category20().range()},
title : {visible : true,text : 'Title2'},
dataset : oDataset});
oStackChart.setModel(oModel);
var oFilter=new sap.ui.model.Filter("SUPPLIERID",sap.ui.model.FilterOperator.EQ,oInput1.getValue());
oStackChart.getBinding("rows").filter(oFilter);
oStackChart.placeAt("content");
Can anyone suggest the change in my code to do so. Kindly help.
Thanks
You can add the filters to the FlattenedDataset like:
var oDataset = new FlattenedDataset({ // required by "sap/viz/ui5/data/FlattenedDataset"
dimensions: aDimensions,
measures: aMeasures,
data: {
path: sEntity,
filters: [ oFilter ],
parameters: {
select: 'ProductID,UnitPrice,Quantity'
}
}
});
Note I used parameters to reduce the columns returned.
I use bootstrap multi-select and I want to update options on flow with ajax
To populate on init my multiselect I do
<select name="model" class="multiselect" multiple="multiple">
<? foreach ($sel_models as $mod) { ?>
<option value="<?= $mod ?>" <?= ($mod == $params['model']) ? 'selected' : '' ?>><?= $mod ?></option>
<? } ?>
</select>
then on event I would like to update my option list with the following ajax
I was trying to use the rebuild method but won't fire the drop-down after creation
$.ajax({
type: 'post',
url: "helper/ajax_search.php",
data: {models: decodeURIComponent(brands)},
dataType: 'json',
success: function(data) {
$('select.multiselect').empty();
$('select.multiselect').append(
$('<option></option>')
.text('alle')
.val('alle')
);
$.each(data, function(index, html) {
$('select.multiselect').append(
$('<option></option>')
.text(html.name)
.val(html.name)
);
});
$('.multiselect').multiselect('rebuild')
},
error: function(error) {
console.log("Error:");
console.log(error);
}
});
With firebug I can see that the list is generated but on select won't show up
In the doc I can read :
.multiselect('setOptions', options)
Used to change configuration after initializing the multiselect. This may be useful in combination with .multiselect('rebuild').
Maybe you can't change your widget data by your initial way. In a correct way you should use setOptions method.
Else : With your way, maybe should you think about destroy your widget .multiselect('destroy') and create it again after.
Update after comment :
In the doc : ( you've linked )
Provides data for building the select's options the following way:
var data = [
{label: "ACNP", value: "ACNP"},
{label: "test", value: "test"}
];
$("#multiselect").multiselect('dataprovider', data);
So :
When you get data from your ajax call, you have to create an array of objects ( it's the options in the select you want to have ) with the format like
var data =
[
{label: 'option1Label', value: 'option1Value'},
{label: 'option2Label', value: 'option2Value'},
...
]
When your objects array is created, then you just have to call the method
$("#multiselect").multiselect('dataprovider', data);
Where data is your array of objects.
I hope I'm clear :/
As an alternative to multiselect('dataprovider', data) you can build the list with jquery append exactly the way you did in your question. The only change you need to make is to delay the rebuild until after the ajax request is complete.
var buildDrivers = $.getJSON('resources/orders/drivers.json', function(data) {
$.each(data, function(i, driver) {
$('#toolbar select[name="drivers"]').append('<option>'+driver+'</option>');
});
});
buildDrivers.complete(function() {
$('.multiselect').multiselect('rebuild');
});
see http://api.jquery.com/jquery.getjson/ for documentation
I've been added the functionality of updating options after filtering and getting them from the server side. This solution relays on the concept of injecting new options, destroying the select and initializing it again.
I took into account:
Considering the existing selected options, which must stay.
Removing duplicate options (might be as a conflict from which that already selected and the new that came from the server).
Keeping the options tray open after the update.
Reassign the previous text in the search text box & focusing it.
Just add the 'updateOptions' as a function after the 'refresh' function along with the two helper functions as follows:
updateOptions: function (options) {
var select = this.$select;
options += this.getSelectedOptionsString();
var selectedIds = select.val(),
btnGroup = select.next('.btn-group'),
searchInput = btnGroup.find('.multiselect-search'),
inputVal = searchInput.val();
options = this.removeOptionsDuplications(options);
if (!options) {
options = '<option disabled></option>';
}
// 1) Replacing the options with new & already selected options
select.html(options);
// 2) Destroyng the select
select.multiselect('destroy');
// 3) Reselecting the previously selected values
if (selectedIds) {
select.val(selectedIds);
}
// 4) Initialize the select again after destroying it
select.multiselect(this.options);
btnGroup = select.next('.btn-group');
searchInput = btnGroup.find('.multiselect-search');
// 5) Keep the tray options open
btnGroup.addClass('open');
// 6) Setting the search input again & focusing it
searchInput.val(inputVal);
searchInput.focus();
},
getSelectedOptionsString: function () { // Helper
var result = '',
select = this.$select,
options = select.find('option:selected');
if (options && options.length) {
$.each(options, function (index, value) {
if (value) {
result += value.outerHTML;
}
});
}
return result;
},
removeOptionsDuplications: function (options) { // Helper
var result = '',
ids = new Object();
if (options && options.length) {
options = $(options);
$.each(options, function (index, value) {
var option = $(value),
optionId = option.attr('value');
if (optionId) {
if (!ids[optionId]) {
result += option[0].outerHTML;
ids[optionId] = true;
}
}
});
}
return result;
},
Demo:
State:
"Option 1"
$('#select').multiselect('updateOptions', '<option value="2">Option 2</option>');
State:
"Option 2"
"Option 1"
I think this is an easier way to add options on the fly (using ajax or any other listener) to an existing Bootstrap MultiSelect.
Following is a simplified example to add options:
function addOptionToMultiSelect(multiselectSelector, value, selected) {
var data = [];
$(multiselectSelector + ' option').each(function(){
var value = $(this)[0].value;
var selected = $(this)[0].selected;
data.push({label: value, value: value, selected: selected});
});
// Add the new item
data.push({label: value, value: value, selected: selected});
$(multiselectSelector).multiselect('dataprovider', data);
}
For simplicity, I have assumed both the label and value are the same in an option. Note that the already selected options are taken care of by reading the selected attribute from the existing options. You can make it more sophisticated by tracking the disabled and other attributes.
Sample:
addOptionToMultiSelect('#multiselect-example', 'new-option', true);
The documentation provides an example:
aContainer = Ember.ContainerView.create({
childViews: ['aView', 'bView', 'cView'],
aView: Ember.View.create(),
bView: Ember.View.create(),
cView: Ember.View.create()
});
This is really neat, however if I want to write a function that adds views when called, how do I name each view that I create? for example:
aContainer = Ember.ContainerView.create({
childViews: [],
newView: function( input ){
var newView = BaseView.create({ field: input });
this.get('childViews').pushObject( newView );
}
});
this seem to push an anonymous view into the container. Any thoughts on how to name it?
For example, it'd be neat to have a snippet that says:
newView: function( input ){
var name = 'view_' + this.get('childViews').get('length') + 1
var newView = BaseView.create({ field: input, meta: name })
this.get('childViews').pushObject( newView );
}
Thank you.
I don't think there's a meta attribute to add named views. But you can always just assign them yourself.
newView: function( input ){
var name = 'view_' + this.get('childViews.length') + 1
var newView = BaseView.create({ field: input });
this.get('childViews').pushObject( newView );
this.set(name, newView);
}