How to use DropDown to sent data - javascript

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.

Related

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

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

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

Laravel - Return with input from a dynamic select menu after validation error

I have a couple of select menus that are populated dynamically by selecting an option from another menu.
because these are populated dynamically, Laravel's withInput function does not return the data that was selected if the form does not pass validation.
Is there a way to return Input from dynamically created field data?
Here is my java script that builds the select menu
$('.admin-select').change(function() {
$.getJSON("/locations/getlocationslist/"+$(this).val(), function(data) {
var location = $('#location');
location.empty();
$.each(data, function(index, element) {
location.append("<option value='"+ element.id +"'>" + element.name + "</option>");
});
$.one(location.prepend("<option>- Select -</option>"));
});
});
This is the function that gets the data for the menu:
public function getlocationslist($id)
{
$company = Company::find($id);
$locations = $company->locations();
return Response::make($locations->get(['id','name']));
}
In my users controllers store function I check validation:
$this->userNewForm->validate(Input::all());
Then the error handler:
App::error(function(Laracasts\Validation\FormValidationException $exception, $code)
{
return Redirect::back()->withInput()->withErrors($exception->getErrors());
});
As the location select menu is dynamically created via AJAX the option isn't there for Laravel to preselect when it reloads the page.
However you can check if an option has been selected on page load for .admin-select and if it has then do the ajax call to refill the dynamic drop down and select the relevant option.

How do you submit the selected value in a dropdown via ajax in Django

Am a little bit newbie to django ajax so my question might be an easy thing for experts.
I have a select option dropdown where i want when the user selects a value from dropdown, the value is submitted via ajax so that i can run querysets in the django backend using the selected value.
I can somehow figure out to do this in the backend but need a little help with how to submit this value in the front end by ajax.
here is the dropdown code,just basic html,
<select>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
I want an ajax function that will send the selected value to server so that i can use it to run a queryset in the django backend and return the result to ajax success function appropriately.
Thanks in adavnce
Here's an example using JQuery that places an event handler on the select widget that will call your Django view when the user makes a selection. In this example the selected name is being appended to the URL so that Django can grab it with the following regex in urls.py:
url(r'^path_to_app/(?P<name>\w+)$', 'app.views.function'),
Here's an example:
<select id="chooseme">
<option>--select a name--</option>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#chooseme').change(function(){
var name = document.getElementById("chooseme").value;
$.get('/path_to_app/' + name, function(data){
// do something here with a return value data, if desired
});
});
});
</script>
Check that:
<select id="select_form">
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
var name = $('#select_form').find(":selected").text();
var url = 'your_url_here'+userName+'/';
$.get(url, function(data)
{
//do something with data
})
I tried like this for the following select dropdown:
<select id="select_dropdown">
<option value='joshua'>joshua</option>
<option value='peter'>peter</option>
....
....
</select>
<script>
$(document).ready(function(){
$('#select_dropdown').change(function(){
var e = document.getElementById("select_dropdown");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "your-url",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>

How to set default value on an input box with select2 initialized on it?

How do I set default value on an input box with select2? Here is my HTML:
<input type="text" id="itemId0" value="Item no. 1">
and my javascript:
$("#itemId0").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
Here is the issue:
If I won't initialize my input box into a select2 box, I can display the default value of my input box which is "Item no. 1":
but when I initialize it with select2 eg. $("#itemId0").select2({code here}); I can't then display the default value of my text box:
Anyone knows how can I display the default value please?
You need to utilize the initSelection method as described in Select2's documentation.
From the documentation:
Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.
In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.
I hope this helps.
Old initial selections with initSelection
In the past, Select2 required an option called initSelection that was
defined whenever a custom data source was being used, allowing for the
initial selection for the component to be determined. This has been
replaced by the current method on the data adapter.
{
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
}
You can use the set value too.
You should directly call .val on the underlying element
instead. If you needed the second parameter (triggerChange), you
should also call .trigger("change") on the element.
$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");
Refs:
https://select2.github.io/announcements-4.0.html
https://github.com/select2/select2/issues/2086
http://jsfiddle.net/F46NA/7/
If you have an input element, declare it as follows. Remember to populate the value field as well.
<input type="hidden" name="player" id="player" data-init-text="bla bla" value="bla bla" >
Write an initSelection function
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"text":elementText,"id":elementText});
}
make sure that this call back has same key value pair as the one return by the ajax call.
callback({"text":elementText,"id":elementText});
I have noticed that keeping the value field empty will keep the input empty by default so remember to populate it as well.
The method initSelection can not have an empty value attribute to work properly.
That was my problem.
Hopefully this will help someone.
You can easily change the value of your select input by just putting the id's of your selected option in data attribute of your select input. And then in javascript
var select = $('.select');
var data = $(select).data('val');
$(select).val(data);
And after that initialize select2 on your select input
$(select).select2();
Here is the fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/
you dont need ajax or json, you just need to put SELETED tag into your OPTION and SELECT2 will display the init value.
This works for me: 'Add default value to the head of array'
data.unshift({'id':-1, 'name':'xxx'});
$('#id_xxx).select2({
placeholder: '--- SELECT ---',
data: data,
allowClear: true,
width: '100%'
});
However, official doc says:
You can set default options by calling $.fn.select2.defaults.set("key", "value").
There is no example though.
I found the extremly simple solution.
You have to pass the ID and the Name of the default option and insert it like HTML inside
var html = ' <option value="defaultID">defaultName</option>';
$(".js-example-basic-single").html(html);
How to get defaultID or defaultName depends on your code.
For instance in ASP .Net MVC you can do it like
<select id="PersonalID" class="js-example-basic-single form-control form-control-sm" name="PersonalID">
<option value="#Model.PersonalID">#ViewBag.PersonalInfo</option>
</select>
I use another approach in this specific configuration:
- multiple="multiple"
- populating from AJAX on user's search
$("#UserID").select2({
placeholder: 'Input user name',
"language": {
"noResults": function () {
return "Sorry, bro!";
}
},
dropdownParent: $("#UserID").parent(),
ajax: {
delay: 200,
url: '#Url.Action("GetUserAsJSON", "AppEmail")',
cache: true,
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
};
// Query parameters will be ?search=[term]&page=[page]
return query;
}
}
});
There are few steps to get working my solution
1) Keep each added value in a global array.
var selectedIDs = new Array();
$("#UserID").on('change', function (e) {
//this returns all the selected item
selectedIDs = $(this).val();
});
2) So when you save data you always have selectedIDs array.
3) When you refresh/load webpage just populate selectedIDs with saved data for later resaving/editing from one hand and from another hand populate select2 object
In my case of ASP MVC it looks like this but you can use JQuery to insert <option> to <select>.
<select id="UserID" class="js-example-basic-multiple form-control border" name="UserID" style="width:100%!important;" multiple="multiple">
foreach (var item in Model.ToUsers)
{
<option selected="selected" id="#item.ID" value="#item.ID">#item.Value</option>
}
</select>

Categories