Dynamically filled HTML select, change selected visual . Blade Laravel template - javascript

I have this code. I'm working in Blade template by Laravel framework.
<select class="form-control" name="id_zupanije" id="id_zupanije" onchange="popuniGradove(this, document.getElementById('id_grada'))">
#foreach($zupanije as $zupanija)
#if($zupanija->id == $idzupanije)
<option value="{{$zupanija->id}}" selected="selected">{{$zupanija->naziv_zupanije}}</option>
#else
<option value="{{$zupanija->id}}" selected="">{{$zupanija->naziv_zupanije}}</option>
#endif
#endforeach
<option value="0" selected="">--Odaberite--</option>
idzupanije is id of the select option that needs to be selected...
javascript function "popuniGradove" is for creating select options for another select.
What I want to know is how to visual update selected option, so when window loads I see created select and showing me selected option, not this one
"--Odaberite--".
EDIT
here is screenshoot of how it looks..
I have 3 selects.. first is Zupanija (eng. "province"), Grad (eng. City), Kvart (eng. quart).. when I select zupanija, select grad is filled with options -> cities that have foregin key id_zupanija in table .. samo for kvart, after city is selected, javascript creates options with proper kvarts
... After I press submit (bnt Filtriraj) I refresh the page and filter results below... but I want my selects to save their choosen options before before submiting.. they keep showing --Odaberite-- (default option, last created) afer submiting..

If I understand you right you could consider using a Package like the old laravel 4 FormBuilder.
E. g. https://github.com/kristijanhusak/laravel-form-builder
That way you can bind every form to the respective model like so:
{!! Form::model($user, array('route' => array('user.update', $user->id))) !!}
Laravel automatically checks if input is existing in cache and will attach that data to the form.

You have to add 2 selectize, in this example we have first one for states (for example) and a second one for cities (for example). when we select a state the page send an ajax request to fetch cities in this state, then we set cities list on the cities' select.
the state select :
<select id="select-cities-state" class="selectized">
<option value="1">State 1</option>
...
</select>
the cities select :
<select id="select-cities-city" class="selectized" disabled="">
<option value=""></option>
</select>
var xhr;
var select_state, $select_state;
var select_city, $select_city;
$select_state = $('#select-cities-state').selectize({
onChange: function(value) {
if (!value.length) return;
select_city.disable();
select_city.clearOptions();
select_city.load(function(callback) {
xhr && xhr.abort();
xhr = $.ajax({
url: 'https://jsonp.afeld.me/?url=http://api.sba.gov/geodata/primary_city_links_for_state_of/' + value + '.json',
success: function(results) {
select_city.enable();
callback(results);
},
error: function() {
callback();
}
})
});
}
});
$select_city = $('#select-cities-city').selectize({
valueField: 'name',
labelField: 'name',
searchField: ['name']
});
select_city = $select_city[0].selectize;
select_state = $select_state[0].selectize;
select_city.disable();

Related

How to use DropDown to sent data

in MVC Application, i use DropDown list by javascript and Json,
here is the script:
//load List
$(document).ready(function () {
$.getJSON("/home/getProfiliList", function (data) {
$.each(data, function (i, data) {
$('<option>',
{
value: data.prof_cena,
text: data.prof_ime
}).html(data.prof_ime).appendTo("#profilID");
});
})
//load price
$(function () {
$("[name='profilID']").on("change", function () {
$("#pr_cena").val($(this).val());
});
});
});
now when i send form to database at this moment save as value of price. Also i need value of price because when choise something from list price load automaticly.
How with this script is possible to send profilID as Text, included this script
here is code of DropDown:
<select name="profilID" id="profilID">
<option value="">- LIST -</option>
</select>
by default when you post the form back it will send the value of the selected option on the select item. set this to the value i.e. the text you want to send back, then to get the price, when you build the options you can add a data- attribute to store the price, which you would then get in your load price function like
$("#pr_cena").val($(this).find(":selected").data('price'));
where your options would look like
<option value="Text" data-price="10.00">Text</option>
the other alternative would be to create your own submit handler for the form and change the formdata for that value of profilID.

How to target a select option based on data attribute?

I'm new to JavaScript and jQuery. I'm trying to create something for a website I'm working on, but I can't figure this out.
How can I get jquery to show or hide a select option of a dropdown, based on the selected data attribute of another dropdown?
IE, selecting option 2 in the first dropdown will show only options 1 and 3 in the second menu, and vice versa?
$(document).ready(function() {
$("#make_id").change(function() {
/* basically if data-make is = to selected data-id option, show option,
if it isn't, hide this option. seems, simple, but I can't figure it out... */
})
})
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 1</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>
$("#make-id").change(function(e){
var currentMake = $("#make-id").data("id");
$("#model-id option").not("[data-make='"+currentMake+"']").hide();
$("#model-id option").filter("[data-make='"+currentMake+"']").show();
}
In English:
Whenever make-id changes, get the data-id field from it.
Select all the options under model-id then filter for ones that don't have the same data-make value. Hide those.
Select all the options under model-id then filter for the ones that do have the same data-make value. Show those.
TL;DR
I've changed the way your code works a little to make it work better for the way you want it to. Take a look at this fiddle.
So first of all, you can easily define a callback on the change event which can filter the second select box's option visibility. One problem you may come into if you do this is that "hidden" options will still be in the select's value if they were previously selected (as in Franz's answer).
Here's a slightly different approach in which everything is emptied and loaded dynamically from a JSON object that you define initially:
1. Define your JSON object (data model)
This could come from a database as well of course.
var makesAndModels = {
"makes": [
{"option_id": 1, "id": 18, "name": "make 1"},
{"option_id": 2, "id": 42, "name": "make 2"}
],
"models": [
{"option_id": 1, "make_id": 42, "name": "make 2: model 1"},
{"option_id": 2, "make_id": 18, "name": "make 1: model 1"},
{"option_id": 3, "make_id": 42, "name": "make 2: model 2"}
]
};
2. Define methods to populate each select
Your rules are simple:
To populate the makes, you need no conditions
To populate the models, you need a make ID (foreign key)
function populateMakes() {
var $make = $('#make_id');
// Remove all options before starting
$make.empty();
// Loop the makes from the JSON data object
$.each(makesAndModels.makes, function(key, make) {
// Append new options for each make
$('#make_id')
.append(
$('<option></option>')
.data('id', make.id) // Assign the data-id attribute
.attr('value', 'make option ' + make.option_id) // Give it a value
.text(make.name) // Give it a label
);
});
}
The function above is simply emptying the #make_id select box, then looping the makes in the JSON data object and appending a new option element to the makes select for each result, setting the attributes as it goes.
Then to populate the models, we do the same thing for models as we did for makes, except we'll ignore any models that are for a different make.
function populateModels(makeId) {
// Assign the selector to a variable to repeated use/Don't Repeat Yourself
var $model = $('#model_id');
// Remove all models in the select to start
$model.empty();
// Loop the models in the JSON object
$.each(makesAndModels.models, function(key, model) {
// Ignore any models for other makes
if (model.make_id != makeId) {
return;
}
// Append the new model to the select
$model
.append(
$('<option></option>')
.data('make', model.make_id) // Assign its data-make attribute
.attr('value', 'model option ' + model.option_id) // Give it a value
.text(model.name) // Give it a label
);
});
}
3. Simplified HTML
Once you've got that framework, your HTML and event handlers are going to be very simple.
The HTML select boxes don't need any options since they're populated dynamically, although you may want to leave the ones you have there already in place to help with older browsers or browsers with Javascript turned off (cringe):
<!-- These are populated dynamically now! -->
<select id="make_id"></select>
<select id="model_id"></select>
4. Create your jQuery event handler
...and glue it all together:
$(document).ready(function() {
// Populate the makes select box
populateMakes();
// Define what should happen when you change the make_id select
$("#make_id").change(function() {
// Find the currently selected make's ID from data-id
var selectedMake = $(this).find('option:selected').data('id');
populateModels(selectedMake);
});
// Trigger a change to populate the models the first time
$('#make_id').change();
});
The trick above is that once you've populated the makes and defined your event handler for when the makes select box changes, you can to trigger the change event manually - this will cause populateModels() to be called with the first make in the list, and have the models for that make populated too.
$(document).ready(function() {
$("#make_id").change(function() {
if ($(this).val()=='make option 2') $("#model_id").find("option").eq(1).hide();
else $("#model_id").find("option").eq(1).show();
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="make_id" >
<option value="make option 1" data-id="18">option 1</option>
<option value="make option 2" data-id="42">option 2</option>
</select>
<select id="model_id" >
<option value="model option 1" data-make="42">option 1</option>
<option value="model option 2" data-make="18">option 2</option>
<option value="model option 3" data-make="42">option 3</option>
</select>

Make select box change values when another value is selected from another select box

I want my select box to change depending which option I choose in the first select, and I want to hide the values that are not from that option/
My HTML here:
<select id="localidad">
#foreach (ja_era.Models.Localidades localidad in ViewBag.localidades)
{
<option value="#localidad.Id">#localidad.Zona</option>
}
</select>
<select name="Localidad" id="barrio">
#foreach (ja_era.Models.Barrios barrio in ViewBag.barrios)
{
<option class="#barrio.Localidad" value="#barrio.Id">#barrio.Barrio</option>
}
</select>
The Localidad select has 4 options and bring the countries, then I have the second select that brings the cities all in one select box. Which ones are well defined in my database.
You can see here that "Barrios" has the column localidad where I insert the localidad id
I have tried some js code but can't figure it out how to make it work.
$(document).ready(function() {
$('#localidad').change(function () {
});
})
Basically you need to get the value of the selected option of the first dropdown, send it to your an action method and let it return the data for the second dropdown in json format. Then you will go through the items in the JSON array and build the markup for the options in the second dropdown.
$(document).ready(function() {
$('#localidad').change(function () {
var v = $(this).val();
var urlToGetData="#Url.Action("GetBarrios","Home")";
var items="";
$.getJSON(urlToGetData+"?id="+v,function(a,item){
items+="<option value='"+item.Value+"'>"+item.Text+"</option>";
})
$("#barrio").html(items);
});
})
Assuming you have GetBarrios action method like this
public ActionResult GetBarrios(int id)
{
var items=db.Barrios.Where(s=>s.Localidad==id)
.Select(s=> new SelectListItem {
Value=s.Id.ToString(),
Text = s.Barrio
}).ToList();
return Json(items,JsonRequestBehaviour.AllowGet);
}

Ng-repeat and auto complete selection with modal window in Angular

I'm doing an application in Angular. It is a Table one row that contain 2 column. Each column contain one select. They are empty. When the user press a button, a modal window shows up and display a grid with all the items (from json) of the first select. When the user click on one rows and press "Confirm", modal window closes filling the first select. In the meanwhile, the second select fill with the subarray of selected item.
In a few words, there are 2 select: you choose the option on the first (by a modal window) and then you choose the item of its subarray in the second select.
Then, the user can add new rows, repeating the select.
I've tried two ways to do this, and they half work. In the FIRST CODE
you can see that, after clicked on modal window, the first select fill it self (even if it is not the first , I don't know why..). And it doesn't not iterate well, because when you choose a item in new line, it modify all the other choises, and I want to prevent this.
<select ng-model="selectedProduct" ng-options="a as a.nome for a in items" ng-change="selectLot(select1)">
<option value="">-- Select Product --</option>
</select>
<select ng-model="selectedLot" ng-options="a as a.value for a in selectedProduct.lots" ng-change="lotSelect(select2)">
<option value="">-- Select Lot --</option>
</select>
The SECOND CODE works better. It iterate well. It change automatically the second item's selection well. But when I press on the modal window, the first selection doesn't automatically fill with the choosen item.
Can you help me? I can't find a solution..... Thank you so much in advice!
The core of the issue is that if you want to have a form that edits elements in an array, you need to have separate models for each of the rows in the array. You can do this by making "selectedProduct" and "selectedLot" into objects that map the array index to the selected value for that row.
I made an updated plunker with a working example, but without looking at it here is a rundown of the changes you would need to make. You need to change your models so they reference something using the array index of the row, and also pass that index into functions that modify the row:
<button class="btn btn-default" ng-click="open($index)">OPEN!!</button>
<select ng-model="selectedProducts[$index]" ng-options="a as a.nome for a in items" ng-change="selectLot(select1, $index)">
<option value="">-- Select Product --</option>
</select>
<select ng-model="selectedLots[$index]" ng-options="a as a.value for a in selectedProducts[$index].lots" ng-change="lotSelect(select2, $index)">
<option value="">-- Select Lot --</option>
</select>
You also want to update the functions in your controller to work with the array indexes:
$scope.selectLot = function(data, index){
$scope.Subarray = [];
for(i=0; i<$scope.items.length; i++){
if(data == $scope.items[i].id){
$scope.Subarray[$index] = $scope.items[i].lots;
$scope.selectedProducts[$index] = $scope.items[i];
break;
}
}
console.log($scope.Subarray);
}
$scope.lotSelect = function(id, $index) {
for(i=0; i<$scope.Subarray[$index].length; i++){
if(id == $scope.Subarray[$index][i].id){
$scope.selectedLots[$index] = $scope.Subarray[$index][i];
break;
}
}
}
And the modal:
$scope.open = function ($index) {
// ...
modalInstance.result.then(function (selectedItem) {
$scope.selectedProducts[$index] = selectedItem;
}, function () {
$log.info('Finestra selezione prodotto chiusa alle ore: ' + new Date());
});
You probably shouldn't be using a SELECT if you are allowing the choice to happen in a modal popup. All you want to do is show the selected item which you can easily do in a number of different ways. Additionally in the first example prodIsChanged(), which is what sets the subarray, is never called. An easier solution may be something like this:
<div>{{mainProduct}}</div>
<select ng-options="a as a.value for a in selectedProduct"></select>
var myApp = myApp.controller('Cntrl', function ($scope,$watch) {
$scope.mainProduct = '';
$scope.selecedProduct = '';
$watch('mainProduct',function(old,new) {
$scope.selectedProduct = ??? // The mainProduct has changed so set the list of sub products as necessary
};
}

Post URL from multiple <select> elements

I have a page with isotope filter. It's using the combination filters with hash history. So whenever multiple filters are selected it updates the URL like this:
example.com/portfolio/#.filter1&.filter4&.filter6
Then I have a search form with multiple 'select' elements:
<form id="search-form" method="post">
<select>
<option value="filter1">Filter Name</option>
<option value="filter2">Filter Name</option>
<option value="filter3">Filter Name</option>
</select>
<select>
<option value="filter4">Filter Name</option>
<option value="filter5">Filter Name</option>
<option value="filter6">Filter Name</option>
</select>
...
<input type="submit" value="Search" />
</form>
I would like to combine the values from all the selected options of each 'select' element into the single URL and redirect to isotope ('portfolio') page with that combined value.
What would be the best way to achieve that? I'm unable to figure it out.
Try this in your js:
var data = { 'filters' : arrayHere };
$.ajax({
type: 'POST',
url: 'your url here',
data: data,
success: function(re) {
console.log('this is your return', re);
}
})
Make an array using $.each, and populate all values inside the array, then post it view ajax call.
1) Keep the selects out of the form and use IDs to access the selected values.
2) Create a hidden input field in the form
3) use onsubmit="mergeSelects()" javascript event.
4) create a function in js
function mergeSelects(){
//get all the values of selects
// append then and generate a string may be
var mergedStringVal = ""; // <--- store values here
// Set it in the hidden input field created in the form and submit them
document.getElementById("mergedSelects").val(mergedStringVal);
}

Categories