on change from jquery is not doing what it supposed to do - javascript

I have 4 Ajax Scripts that update chained dropdowns based on other one selections
<script type="text/JavaScript">
//get a reference to the select element
$select = $('#building');
//request the JSON data and parse into the select element
$.ajax({
url: '/api/get_building/',
dataType:'JSON',
success:function(data){
//clear the current content of the select
//iterate over the data and append a select option
$.each(data, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
function getunit() {
//get a reference to the select element
$select = $('#unit');
$id_lease = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var c_id = ($("select[name='building'] option:selected").attr('value'));
c_url = "/api/get_unit/"+c_id+"/";
$.ajax({
url: c_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select unit </option>');
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
getlease();
},
});
}
function getlease() {
//get a reference to the select element
$select = $('#id_lease');
$id_leaseterm = $('#id_leaseterm');
//request the JSON data and parse into the select element
var s_id = ($("select[name='unit'] option:selected").attr('value'));
s_url = "/api/get_lease/"+s_id+"/";
$.ajax({
url: s_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1"> Select lease</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>');
})
},
});
}
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>');
})
},
});
}
</script>
And the following controls in my form I am updating
<select name="building" id="building" onchange="getunit();">
<option id="-1">Select building</option>
</select>
<select name="unit" id="unit" onchange="getlease();">
<option id="-1">Select unit</option>
</select>
<select class="select" id="id_lease" name="lease">
<option value="" selected="selected">---------</option>
</select>
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="" selected="selected"></option>
</select>
My problem is that when I update the dropdown id_lease it dosent have the on change call. (it is automatically generated from backend)
So for this reason I am adding this line with jquery line in script
$("#lease_id").on("change", getleaseterm());
but it gives me an error 404 that cannot find the values for "get_leaseterm" since I assume it get triggered when page is loading. And all my script are not loading.
So problem is in this last line. How can I solve it?

As Pointy specified removing the () helped as well I was calling wrong id
final version that worked is:
$("#id_lease").on("change", getleaseterm);

Related

how to take data[index] value in ajax?

Sorry but it's my first time with javascript and ajax
I have this code where i print a list from db in an html select
ajax
'''
$.ajax({
type: 'GET',
url: 'birthplace/list',
dataType: 'json',
success: function(data) {
$.each(data, function(i) {
$('#selectBirthplace').append(
'<option id="' + data[i] + '" value="' + data[i] + '">'
+ data[i].nome + '</option>'
);
});
}
});
'''
html
'''
<div class="item3">
<label for="">Birthplace</label>
<select required class="custom-input" id="selectBirthplace" >
<option value="" selected disabled hidden>Select birthplace</option>
</select>
</div>
'''
Birthplace is a parameter of User but it's still a class.
This is part of a user insert form page.
How can i save the value of data[i] in a variable when the select option was chosen?
i tried with data[i].variable, data[i].class but nothing.

How to avoid ajax result on select box

As you in sample above I have placeholder (option without value) to say eg. Select Subcategory but as soon as I change my category value result of subcategories will show.
What I want is when I select category in subcategory dropdown still says Select Subcategory but under that be loaded result of chosen category. In simple words:
Instead of showing results directly, shows placeholder option and
results be under it.
here is my codes:
// HTML
<label for="specification_id">specifications</label>
<select name="specification_id" class="form-control">
<option value="">Select Specification</option>
</select>
// JAVASCRIPT
<script type="text/javascript">
$(document).ready(function() {
$('select[name="subcategory_id"]').on('change', function() {
var subcategoryID = $(this).val();
if(subcategoryID) {
$.ajax({
url: '{{ url('getspecifications') }}/'+encodeURI(subcategoryID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="specification_id"]').empty();
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+ value['id'] +"'>"+ value['title'] +"</option>"
);
});
}
});
}else{
$('select[name="specification_id"]').empty();
}
});
});
</script>
After emptying out the item make sure to append the blank placeholder back in it:
else{
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
}
or just skip it when clearing the select in the first place:
else{
$('select[name="specification_id"]').not(':first').remove();
}
i forgot the empty() in the success: function:
success:function(data) {
$('select[name="specification_id"]').not(':first').remove();
//...
or:
success:function(data) {
$('select[name="specification_id"]').empty().append("<option value='' selected>Select Specification</option>");
//...
Here your option values are empty because you Call empty function.
So you can dynamically select option "Select specification "
Following procedure works fine for me, try this way
success:function(data) {
$('select[name="specification_id"]').empty();
$('select[name="specification_id"]').append("<option
class='form-control' selected value=' '>Select
Specification </option>" );
$.each(data, function(key, value) {
$('select[name="specification_id"]').append(
"<option class='form-control' value='"+
value['id'] +"'>"+ value['title'] +"</option>"
);
});
Thank you

laravel ajax sending and returning at the same page

What I'm trying to do is to create one-page checkout, and the part i get my courier cost i'm facing issue.
I want to send destination city id to controller and get back cost result from controller in order to let user select which way he/she wants to ship his/her product.
Sample from some live website:
Imgur
Ibb
I'm using third-party website data, nothing stored in my database such
as country province city methods or even shipping prices
codes:
My page index function (where everything will show
public function index(Request $request) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxxxx');
$province = $rajaongkir->province();
return view('front.raja', compact('province'));
}
route of it:
Route::get('/raja', 'RajaongkirController#index')->name('raja');
My cities function (where i get cities list based on province selected):
public function getCityList($province)
{
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxx');
$city = $rajaongkir->city($province);
return response()->json($city);
}
route of it:
Route::get('/get-city-list/{province}','RajaongkirController#getCityList');
Cost data function (here is where supposed to return price methods base on selected city):
public function indexajax(Request $request, $cityID) {
$rajaongkir = new Rajaongkir\Domestic('xxxxxxxxxxxxx');
$province = $rajaongkir->province();
$origin = 152; //Jakarta
$destination = $request->cityID;
$weight = 1;
$courier = 'tiki'; // jne, tiki, pos
$cost = $rajaongkir->cost($origin, $destination, $weight, $courier);
return view('front.raja', compact('province', 'cost'));
}
route of it:
Route::get('/rajaajax/{cityID}', 'RajaongkirController#indexajax');
PS: City Id that comes from ajax supposed to be value of
$destination where i put $destination = $request->cityID;
view
this part shows 2 select input where i choose provinces and cities
//HTML
<select name="province" id="">
<option class="form-control" value="">Select Province</option>
#foreach ($province->data as $info)
<option value="{{$info->province_id}}">{{$info->province}}</option>
#endforeach
</select>
<select name="city" id="">
<option class="form-control" value="">Select City</option>
</select>
//JavaScript
<script type="text/javascript">
$(document).ready(function() {
$('select[name="province"]').on('change', function() {
var provinceID = $(this).val();
if(provinceID) {
$.ajax({
url: '{{ url('get-city-list') }}/'+encodeURI(provinceID),
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="city"]').empty();
$.each(data.data, function(key, value) {
$('select[name="city"]').append('<option id="city_id" class="form-control" value="'+ value['city_id'] +'">'+ value['city_name'] + ' - ' + value['type'] +'</option>');
});
}
});
}else{
$('select[name="city"]').empty();
}
});
});
</script>
Cost view codes
here is my loop to show costs when have city id (tested on static $destination id)
Destination:
{{$cost->meta['destination']->province}}, //destination province
{{$cost->meta['destination']->type}}, //destination type such as city or restrict
{{$cost->meta['destination']->city_name}}, //destination city name
{{$cost->meta['destination']->postal_code}}. //destination postal code
#foreach($cost->data as $option)
<h3>{{$option->code}} <small>{{$option->name}}</small></h3>
#foreach($option->costs as $cost)
#foreach($cost->cost as $c)
<label class="radio">
<input name="post" value="{{ $c->value }}" type="radio">{{$cost->service}} / {{ $c->value }} Rp - {{ $c->etd }} hari #if(!empty($c->note))- {{ $c->note }} #endif
</label>
#endforeach
#endforeach
#endforeach
Result will be like so:
PS:: I think: Cost part must be looped in controller because when i
put it in blade (and user didn't choose city yet, it gives error of
undefined/non-object cost) - Just thought :)
Anyone has idea how can i get that cost part after choosing city?
SOLVED
I've changed my cost to:
return response()->json($cost);
And added this JS to my view:
<script>
jQuery( document ).ready( function( $ ) {
$('body').on('change', 'select[name="city"]', function(e){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') }
});
var cityID = $(this).val();
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').append(
'<p>Destination: ' + data['meta']['destination']['province'] + ' , ' + data['meta']['destination']['type'] + ' , ' + data['meta']['destination']['city_name'] + ' , ' + data['meta']['destination']['postal_code'] +'</p>'
);
$.each(data.data, function(key, value) {
console.log();
$('#info').append('<h3>'+ value['code'] + '<small>' + value['name'] +'</small></h3>');
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value2['service'] + ' - ' + value3['value'] + ' - ' + value3['etd'] +'</option>');
});
});
});
}
});
}else{
console.log(data);
}
});
});
</script>
Also Added this to my view:
<div id="calcul" style="margin-top: 30px;">
<div id="des"></div>
<dev id="info"></dev>
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
</div>
However I would like to have radio button instead of drop-down but is OK :).
Hope it help others.

MVC Dropdownlist Cascade - how to fire event on third ddl when first ddl selection changes?

I have three DDL's in a view. I fire a javascript function on 'onchange' of the first DDL to populate the second, and of the second to populate the third. Works fine.
Problem is, when first DDL is set to unselected i.e. "Select a Value", the second DDL gets fired and sets itself to "Select a Value", but the second DDL 'onchange' event does not fire, so the third DDL remains populated with the data that it got from the previous selection.
How do I get the second DDL to fire an event I can use to refresh the third DDL? Or is there another way?
Code below:
#{
ViewBag.Title = "CascadingList";
Layout = "~/Views/Shared/_Layout.cshtml";
}
#{Html.EnableUnobtrusiveJavaScript(true);}
<script type="text/javascript">
$(document).ready(function () {
getMarket();
});
function getMarket() {
var url = '#Url.Content("~/Strategies/MarketList")/';
$.getJSON(url, function (data) {
var items = "<option>Select a Market</option>";
$.each(data, function (i, market) {
if (market.Value.indexOf("\'") > -1) {
s = market.Value + " " + market.Text;
alert(s + ": Market.Value cannot contain \'")
}
items += "<option value='" + market.Value + "'>" + market.Text + " </option>";
});
$('#MarketsID').html(items);
});
}
function getShareType() {
var url = '#Url.Content("~/Strategies/ShareTypeList")/' + $('#MarketsID').val();
$.getJSON(url, function (data) {
var items = '<option>Select an Asset Type</option>';
$.each(data, function (i, shareType) {
items += "<option value='" + shareType.Value + "'>" + shareType.Text + " </option>";
});
$('#ShareTypesID').html(items);
});
}
function getShare() {
var url = '#Url.Content("~/Strategies/ShareList")/' + $('#MarketsID').val() + '|' + $('#ShareTypesID').val();
$.getJSON(url, function (data) {
var items = '<option>Select a Share</option>';
$.each(data, function (i, share) {
items += "<option value='" + share.Value + "'>" + share.Text + "</option>";
});
$('#SharesID').html(items);
});
}
</script>
<h2>Strategy</h2>
<div id="MarketsDivID">
<label for="Markets">Markets</label>
<select id="MarketsID" name="Markets" onchange="getShareType()"></select>
</div>
<div id="ShareTypesDivID">
<label for="ShareTypes">ShareTypes</label>
<select id="ShareTypesID" name="ShareTypes" onchange="getShare()" ></select>
</div>
<div id="SharesDivID">
<label for="Shares">Shares</label>
<select id="SharesID" name="Shares" ></select>
</div>
Try selecting a value for the select after populating it using $('#selectID').val(), if that doesn't work trigger onchange like this ; $('#selectID').trigger('change')
Thanks - I tried that and went around in circles - but it made me think differently. Fixed it by adding a call to the function that populates the third DDL in the function that populates the second DDL - that way it always gets called.
function getShareType() {
var url = '#Url.Content("~/Strategies/ShareTypeList")/' + $('#MarketsID').val();
$.getJSON(url, function (data) {
var items = '<option>Select an Asset Type</option>';
$.each(data, function (i, shareType) {
items += "<option value='" + shareType.Value + "'>" + shareType.Text + "</option>";
});
$('#ShareTypesID').html(items);
});
**** Added This ****
getShare();
}

How to retrieve a value of a selected Item from a dropdown List?

How to i get a value of a selected ITEM from a drop down list ? I'm reading my values a SQL Table using a Stored Procedure ,Once the list is populated i want to take the selected ITEM and save the SQL TABLE. Any help will be much appreciated. Here is what i've tried :
function QueryKomaxDetails() {
$.ajax({
url: GET_SCHEDULE_DEPARTMENTS,
data: 'includeInactive=' + null,
dataType: 'json',
success: LoadKomaxDetails
});
}
var LoadKomaxDetails = function (data) {
var dllItems = eval(data);
var komaxDetails = $("#ddlItems").val();
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});
}
And i managed to get ITEM as a dropdown list.
Here is my HTML code as follows :
<label>Select Komax :</label><select id="ddlItems" name="komax" ></select>
Try this,
var komaxDetails = $("#ddlItems");
$.each(dllItems, function () {
komaxDetails.append("<option value='" + this.departmentId + "'>" + this.departmentName + "</option>");
});

Categories

Resources