Laravel 5.2 Dynamic dropdown select not populating (javascript) - javascript

I have two selects country, and information. The selected_country variable is passed to getInfo() which queries all rows matching that country and returns the deptname and id. The id is the option value in the select and is stored in the database,and deptname is the text displayed in the select. Right now my info dropdown is empty and I am not getting any errors.
public function getInfo()
{
$country = Input::get('selected_country');
$info = Department::where('addressCountry', $country)->orderBy('country')->pluck('deptname', 'id');
return response()->json($info);
}
route
Route::get('related-info', ['as' => 'related-info', 'uses' => 'Auth\AuthController#getInfo']);
Javascript
$('#addressCountry').on('change', function (e) {
var slots = $('#info');
slots.empty();
var selected_country = e.target.value;
$.get("related-info?selected_country=" + selected_country, function (data) {
slots.empty();
console.log(data);
$.each(data.slots, function (index, value) {
slots.append('<option value="' + value.id + '">' + value.name + '</option>');
});
});
});
Relavent parts of my view
<form class="form-horizontal" role = "form" method = "POST" action = "{{ url('/register') }}" > {!!csrf_field() !!}
<select class="form-control" name = "addressCountry" id = "addressCountry" ></select >
<select class="form-control" name = "addressProv" id = "addressProv" ></select >
<select id="info" class="form-control" name="info">
<option value=""></option>
</select>
Also in my view in the scrips section
populateCountries('addressCountry', 'addressProv');
The country and state drop downs are populated using a javascript file its too large to paste here
http://pastebin.com/9XUTPEVY
EDIT: After returning a json response in getInfo instead of the view, if I navigate directly to related-info?selected_country=Ireland it will show the id and name of each one. If I goto /register and select Ireland in the dropdown the dropdown does not populate but the response tab in the network console in firedebug shows the id and name of each. I also changed console.log(data); to alert(data) the pop up says [object Object] when selecting Ireland.
Here are 3 screenshots of output
http://imgur.com/a/jEfuu

All seems right except that you return a view instead of a Json object as response.
Try to replace:
return view('auth.register', ['info' => $info]);
With:
return response()->json($info);

Change the javascript code to this :
$('#addressCountry').on('change', function (e) {
var selected_country = e.target.value;
$.get('related-info?selected_country=' + selected_country, function (data) {
console.log(data);
$('#deptInfo').empty();
$.each(data, function (index, subcatObj) {
$('#info').append('<option value="' + subcatObj.id + '">' + subcatObj.name + '</option>');
});
});
})
I see that when you are going directly to the url, you are going to : related-info?selected_country=Ireland but in javascript, you go to:
related-info?country=' + selected_country but I guess you need to go to : related-info?selected_country

Related

Logging the selected from HTML list and use it as key in populating another

I'm trying to populate two dynamic Lists from two different JSON APIs , Where I need the first selected option to be used as the key to populate the second List.
HTML :
<p>
<input type="button" value="Fill SELECT Dropdown List with JSON" id="bt" />
</p>
<select id="clist" >
<option value="">-- Select --</option>
</select>
<select id="plist">
<option value="">-- Select --</option>
</select>
<p id="client_name"></p>
JS:
$(document).ready(function () {
$('#bt').click(function () {
var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";
$.getJSON(url1, function (data) {
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#clist').append('<option value="' + value.ID + '">' + value.Client + '</option>');
});
});
});
});
$('#clist').change(function () {
$('#client_name').text(this.options[this.selectedIndex].text);
var s_name=this.options[this.selectedIndex].text ;
});
$(document).ready(function () {
$('#clist').change(function () {
var url2 = "https://script.google.com/macros/s/AKfycbz91DIwPh3n4A7gtyV7iTrGxT7t23FMJES3n-ruvxHcfsFEXuBL/exec";
$.getJSON(url2, function (data2) {
$.each(data2, function (index2, value2) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#plist').append('<option value="' + value2.ID + '">' + value2[s_name] + '</option>');
});
});
});
});
I was able to log the value and make a dynamic change and it works for the element Client_name but it doesn't work when populating the second list and returns undefined.
Note :
The selected option from the first key is exactly matching the available keys in the second list
Here is the solution for you question:
You need to just check if the key exists in value2 array.
Running code: https://jsfiddle.net/sfhogj7a/2/
Javascript:
var s_name =''; // make global
$(document).ready(function () {
$('#bt').click(function () {
var url1 = "https://script.google.com/macros/s/AKfycbx91EB9aIOXRYNmP108ZcPuEGgUqZWZli0KWdj5A3Ts0Qc6hrc/exec";
$.getJSON(url1, function (data) {
$.each(data, function (index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
$('#clist').append('<option value="' + value.ID + '">' + value.Client + '</option>');
});
});
});
});
$('#clist').change(function () {
$('#client_name').text(this.options[this.selectedIndex].text);
s_name=this.options[this.selectedIndex].text ;
});
$(document).ready(function () {
$('#clist').change(function () {
console.log('list')
var url2 = "https://script.google.com/macros/s/AKfycbz91DIwPh3n4A7gtyV7iTrGxT7t23FMJES3n-ruvxHcfsFEXuBL/exec";
$.getJSON(url2, function (data2) {
$.each(data2, function (index2, value2) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
if(value2[s_name]){ // check if exists
$('#plist').append('<option value="' + value2.ID + '">' + value2[s_name] + '</option>');
}
});
});
});
});

How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax?

In models I have calculated field total
And I want to see this field in my dynamic drop boxes generated with Ajax.
But I just get undefined in dropdown.
My data flows in following way:
1-I have sterilizer in my api
class LeaseTermSerializer(serializers.ModelSerializer):
class Meta:
model=LeaseTerm
fields = '__all__'
2-I have api method in view
#api_view(['GET']) #csrf_exempt def get_leaseterm(request, tid):
leasetermobj = LeaseTerm.objects.filter(lease=tid,is_active = True)
leaseterm_serializer = LeaseTermSerializer(leasetermobj, many=True)
response = Response(leaseterm_serializer.data)
return Response(response.data,status=status.HTTP_200_OK)
3-In my template I build it like this
function getleaseterm() {
//get a reference to the select element
$select = $('#leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.id + val.total + '</option>');
})
},
});
}
How can I see my my calculated field from model in the drop down that was dynamically generated with Ajax?

Dynamically build AJAX dropdown resets to original state when trying to save with django form?

I my form I have few dropdowns chained between them with AJAX.
This is how I a populating them
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
And this is the control
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="-1" selected="selected">-----</option>
</select>
It all works , I am changing values in my dropdowns and options of other dropdowns are updated.So I can select the relevant value.
The problem is when I Save the for - the form gets not the value that I have put there but the default value that was there before any manipulation of Ajax have been done.
Also when I do view source I see in the code is default value and not what was selected from what I have build with AJAX.(Even that on the screen I do see the correct values in the select options...)
My backend is Django .
My Django form formatted in following way.
class MassPaymentForm(forms.ModelForm):
leaseterm = forms.ModelChoiceField(queryset=LeaseTerm.objects.none()) # Need to populate this using jquery
lease= forms.ModelChoiceField(queryset=Lease.objects.none()) # Need to populate this using jquery
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
What could be the problem ? And any idea how to solve it?
I have figured out what was the problem
it is in my form file
If I keep the lease and leaseterm fields just in Meta class that it doesn't reset those fields on submit any more . And all my logic finally works as designed.
class MassPaymentForm(forms.ModelForm):
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']

Meteor: use dropdown menu to get data from mongodb and show results

I'm new from Meteor, and I need to realize a little dropdown menu and a search with the selected data in the dropdown menu.
I have devices.html :
<div class="ha_panel-selections">
<form id="plane-form">
<select id="plane-select">
<option disabled="disabled" selected="selected">Please Select</option>
{{#each plane}}
<option id="plane_selected" value="{{this}}">{{this.planeid}}</option>
{{/each}}
</select>
</form>
</div>
the data comes from the database: devices.js is:
Template.devices.helpers({
plane: function() {
return plane.find({});
}
});
Now what I want to do is take the selected value in the dropdown menu (the plane.planeid value), search in the db for that value, and print the data associated:
so for example, if I select "plane1" I can see planeid, flighttime, pilotname, ecc; if I change from "plane1" to "plane2" the data will change accordingly.
How can I pass the plane_selected value from html to devices.js? and back, once i will find the data in the db, how can I print the results passing the data form devices.js to devices.html ?
I think it should be (in devices.js) something like
Template.devices.events({
"change #plane-form": function (event, template) {
//console.log("event: " + util.inspect(event) );
//console.log("template: " + util.inspect(template) );
var selected = Session.get("plane_selected");
console.log("selected: " + selected);
}
});
What I'm doing wrong?
Taking into account that you're able to select the planeid, you're pub/sub seems to be working. All you need is another helper that give you back the rest of the plane's data.
devices.js
Template.devices.events({
"change #plane-select": function (event, template) {
var selected = event.target.value;
console.log("selected: " + selected);
Session.set("selectedPlane", selected);
}
});
Template.devices.helpers({
plane: function() {
return plane.find({});
},
planeData: function() {
return planes.findOne({
planeId: Session.get("selectedPlane")
});
}
});
devices.html
<p>
planeID: {{planeData.planeid}}
planeName: {{planeData.planeName}}
...
...
</p>
Note: It's up to you to use Session or reactive vars Session variables are lost on page refresh.

Getting stuck in a loop on .change - Select2 Drop Down Lists

I have 2 drop down lists. One for people and one for businesses. If you select a person from the list it will automatically query the database and then select the correct corresponding business that is associated with that person. If you select a business, it will automatically query the database for all the people that are associated with that company. Then it clears the current list of people and appends the associated people.
This is all works great...until I wanted to use Select2 to make my drop down lists easily searchable. I now get stuck in an infinite loop because the Select2 uses the .val().trigger('change') method to select the value you want. When that's triggered it also triggers the .change function that runs the queries and populates the fields.
What can I do to fix this?
Here is my code:
$('#personNameField').select2();
$('#businessNameField').select2();
/* When a business is selected it then pulls all the associated customers and puts them into the customer name drop down list */
$("#businessNameField").change(function getAssociatedPeople() {
var sitePath = sitepath.sitePath;
var business_id = $("#businessNameField").val();
if (business_id == 'Choose a Company') {
$('#personNameField').val('Choose a Person').trigger('change');
}
else {
/* Location of the query script that pulls info from the database */
var url = myticketsscript.pluginsUrl + '/portal/public/includes/shortcodes/my-tickets/auto-complete/auto-complete.php';
$.get( url, { business_id: business_id, sitePath: sitePath } )
.done(function( data ) {
$('#personNameField').html('<option value="Choose a Person">Choose a Person</option>');
var results = jQuery.parseJSON(data);
console.log(data);
$(results).each(function(key, value) {
/* Add the data to the customer name drop down list */
$('#personNameField').append('<option id="customer_id" value="'+ value.id +'">' + value.first_name + ' ' + value.last_name + '</option>');
/* Logs the data in the console */
console.log(key);
console.log(value);
})
});
}
});
/* When a person is selected it then pulls all the associated business and puts it into the business name drop down list */
$("#personNameField").change(function() {
var customer_id = $("#personNameField").val();
var sitePath = sitepath.sitePath;
if (customer_id == 'Choose a Person') {
var url = myticketsscript.pluginsUrl + '/portal/public/includes/shortcodes/my-tickets/auto-complete/auto-complete.php';
$.get( url, { customer_list: customer_id, sitePath: sitePath } )
.done(function( data ) {
$('#businessNameField').val('Choose a Company').trigger('change');
$('#personNameField').html('<option value="Choose a Person">Choose a Person</option>');
var results = jQuery.parseJSON(data);
console.log(data);
$(results).each(function(key, value) {
/* Add the data to the customer name drop down list */
$('#personNameField').append('<option id="customer_id" value="'+ value.id +'">' + value.first_name + ' ' + value.last_name + '</option>');
/* Logs the data in the console */
console.log(key);
console.log(value);
})
});
}
else {
/* Location of the query script that pulls info from the database */
var url = myticketsscript.pluginsUrl + '/portal/public/includes/shortcodes/my-tickets/auto-complete/auto-complete.php';
$.get( url, { customer_id: customer_id, sitePath: sitePath } )
.done(function( data ) {
var results = jQuery.parseJSON(data);
console.log(data);
$(results).each(function(key, value) {
/* Selects the correct company for the customer selected */
$('#businessNameField').val(value.id).trigger('change');
console.log(key);
console.log(value);
})
});
}
});
Not having used Select2 before myself, I looked into their docs and found that they have some of their own events.
https://select2.github.io/examples.html#programmatic-control
So rather than binding the selectors to change, perhaps you want to try something like:
$("#businessNameField").on("select2:select", function () {...});
$("#personNameField").on("select2:select", function () {...});
I just tried it on this little example below. I got the infinite loop when using change, but once I used the proper events, it didn't loop.
Note that I navigated the nested object to get at the value and text of each select option; e.params.data.id and e.params.data.text, where e is the event passed to the callback.
It's kind of a silly little example where selecting one option will arbitrarily select an option in the other select, but you get the idea. Hope this helps.
<!DOCTYPE html>
<html>
<head>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var firstSelect = $(".js-example-basic-single1")
firstSelect.select2();
var secondSelect = $(".js-example-basic-single2")
secondSelect.select2();
firstSelect.on("select2:select", function (e) {
var value = e.params.data.id;
var text = e.params.data.text;
console.log("firstSelect selected value: " + value);
if (value === "AL") {
secondSelect.val("MA").trigger("change");
}
else if (value === "WY") {
secondSelect.val("CA").trigger("change");
}
});
secondSelect.on("select2:select", function (e) {
var value = e.params.data.id;
var text = e.params.data.text;
console.log("secondSelect selected value: " + value);
if (value === "MA") {
secondSelect.val("AL").trigger("change");
}
else if (value === "CA") {
secondSelect.val("WY").trigger("change");
}
});
});
</script>
</head>
<body>
<select class="js-example-basic-single1">
<option value="Default">Default</option>
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
</select>
<select class="js-example-basic-single2">
<option value="Default">Default</option>
<option value="MA">Massachusetts</option>
<option value="CA">California</option>
</select>
</body>
</html>

Categories