Display value in dropdown based on first dropdown - javascript

I have a working form here which populating dropdown from the database, i want to do here is display the value of 2nd dropdown based on the selected value on the 1st dropdown, but how i'm gonna do it. My Class will only display on the 2nd drowpdown if error is selected which the 1st dropdown
//my screenshot, my only sample data
enter image description here
Backend code:
public JsonResult GetErrorCategory()
{
List<ErrorCategory> error = errorDataAccessLayer.GetAllError(Action);
return Json(error.Select(x => new
{
errorCode = x.ErrorCode,
errorDescription = x.ErrorDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
public JsonResult GetClassCategory()
{
List<ErrorClass> error = errorDataAccessLayer.GetAllClass(Action);
return Json(error.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}
View:
<form id="ticket_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="form-group col-md-4">
<label><strong>Error Type</strong></label>
<select name="ErrorType" id="ErrorDropdown" class="form-control ErrorType" >
</select>
</div>
</div>
<div class="row">
<div class="form-group col-md-4">
<label><strong>Class Type</strong></label>
<select name="ClassType" id="ClassDropdown" class="form-control ClassType" >
</select>
</div>
</div>
<div class="form-group">
<input type="submit" id="addTicket" value="Create" class="btn btn-md btn-outline-secondary" style="margin:auto;display:block;" />
</div>
</form>
Javascript code:
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
}
});
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
});
</script>

First, in script section you need split functions like as following. You see I added code parameter to the second GetClassCategory method:
function GetErrorCategory() {
$.ajax({
type: "POST",
url: "/Ticket/GetErrorCategory",
data: "{}",
success: function (data) {
var s = 'option value="-1">Please Select Error Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].errorDescription + '">' + data[i].errorDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ErrorDropdown").html(s);
// This line applies onchange event for errorcategory dropdown
ApplyErrorCategoryDropDownOnChange();
}
}
}
function GetClassCategory(code) {
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: JSON.stringify({ code: code }),
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
}
Second, you need handle onchange() event, because when another item of the first dropwdown selected then you need get it's value.
function ApplyErrorCategoryDropDownOnChange() {
$("#ErrorDropdown").change(function (data) {
GetClassCategory(this.value)
});
}
Third, you must call GetErrorCategory() method from document ready function.
$(function () {
GetErrorCategory();
});
Fourth, you need add code parameter in the backend section, and apply this parameter to your db query:
public JsonResult GetClassCategory(string code) // I added parameter
{
List < ErrorClass > error = errorDataAccessLayer.GetAllClass(Action);
return Json(
error
.Where(x => x.ClassCode = code) // I added this section
.Select(x => new
{
classCode = x.ClassCode,
classDescription = x.ClassDescription
}).ToList(), JsonRequestBehavior.AllowGet);
}

You have to change your code in your second ajax call, i mean it should be some dependent conditional to the first dropdown, For that you just need to get the value of the first dropdown to the second dropdown ajax call while it is selected. Just i mention below :
var error=document.getElementById("ErrorDropdown").value;
$.ajax({
type: "POST",
url: "/Ticket/GetClassCategory",
data: "{error:error}",
success: function (data) {
var s = 'option value="-1">Please Select Class Type</option>';
for (var i = 0; i < data.length; i++) {
s += '<option value="' + data[i].classDescription + '">' + data[i].classDescription + '</option>';
}
s += '<option value="Others">Others</option>';
$("#ClassDropdown").html(s);
}
});
Here i have the value of the first dropdown in variable named as error and i have passed it through the ajax call and use it in my database query with where clause.

Related

Laravel: Auto populate dropdown select with AJAX is returned undefined

So I have tried auto populated dropdown in Laravel. I'm on the half way to complete this, I think so.. So basically I have 3 select dropdown list which is dependent on the first dropdown. the second dropdown list is return as expected, but the other one / the third dropdown is returned undefined list. I haven't find the solution or any clue to fix this. I hope I get the appropriate hints or directions to solve this. Thank You
Here's my dropdown in View
<div class="form-group row">
<label for="nm_cust" class="col-sm-2 col-form-label">Nama Customer</label>
<div class="col-sm-4">
<select name="nm_cust" id="nm_cust" class="form-control" required>
<option value="">Pilih</option>
#foreach ($customer['data'] as $cust)
<option value="{{ $cust->nm_cust }}">{{ $cust->nm_cust }}
</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row">
<label for="alamat" class="col-sm-2 col-form-label">Alamat</label>
<div class="col-sm-4">
<select name="alamat" id="alamat" class="form-control" required>
<option value="">Pilih</option>
</select>
</div>
</div>
<div class="form-group row">
<label for="no_psn" class="col-sm-2 col-form-label">Nomor Pemesanan</label>
<div class="col-sm-4">
<select name="no_psn" id="no_psn" class="form-control" required>
<option value="">Pilih</option>
</select>
</div>
</div>
and this is my controller
public function index()
{
$customer['data'] = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->get();
$barang = \App\Barang::All();
$pemesanan['data'] = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->get();
// $temp_kirim = Temp_pengiriman::All();
//No otomatis untuk transaksi pengiriman
$AWAL = 'DLV';
$bulanRomawi = array("", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12");
$noUrutAkhir = \App\Pengiriman::max('no_kirim');
$no = 1;
$no_kirim = sprintf("%03s", abs((int)$noUrutAkhir + 1)) . '/' . $AWAL . '/' . $bulanRomawi[date('n')] . '/' . date('Y');
$pengiriman = Pengiriman::orderBy('no_kirim', 'DESC')->paginate(5);
return view('pengiriman.pengiriman',
[
'no_kirim' => $no_kirim,
'customer' => $customer,
'barang' => $barang,
'pemesanan' => $pemesanan,
// 'temp_kirim' => $temp_kirim,
'pengiriman' => $pengiriman
]
);
}
public function getCustomer($nm_cust="")
{
$custData['data'] = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->where('nm_cust',$nm_cust)
->get();
return response()->json($custData);
}
public function getNoPsn($nm_cust="")
{
$noPsnData['data'] = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->where('nm_cust',$nm_cust)
->get();
return response()->json($noPsnData);
}
and this is my AJAX to get the dropdown list
<script type='text/javascript'>
$(document).ready(function() {
// Department Change
$('#nm_cust').change(function() {
// Department id
var nm_cust = $(this).val();
// Empty the dropdown
$('#alamat').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'pengiriman/' + nm_cust,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response['data'] != null) {
len = response['data'].length;
}
if (len > 0) {
// Read data and create <option >
for (var i = 0; i < len; i++) {
var nm_cust = response['data'][i].nm_cust;
var alamat = response['data'][i].alamat;
var option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#alamat").append(option);
}
}
}
});
});
});
$(document).ready(function() {
// Department Change
$('#nm_cust').change(function() {
// Department id
var alamat = $(this).val();
// Empty the dropdown
$('#no_psn').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'pengiriman/' + alamat,
type: 'get',
dataType: 'json',
success: function(response) {
var len = 0;
if (response['data'] != null) {
len = response['data'].length;
}
if (len > 0) {
// Read data and create <option >
for (var i = 0; i < len; i++) {
var alamat = response['data'][i].nm_cust;
var no_psn = response['data'][i].no_psn;
var option = "<option value='" + no_psn + "'>" + no_psn +
"</option>";
$("#no_psn").append(option);
}
}
}
});
});
});
</script>
I put that script in the views. Please help me solve this problem or give any clue to fix this.
// I forgot my route to put into this section sorry guys
And this is my routes. so I just change parameter on 3rd route below, which is name('pengiriman.getNoPsn), to /{alamat} depends on my AJAX but still no effect.
//pengiriman
Route::get('/pengiriman', 'PengirimanController#index')->name('pengiriman.pengiriman')->middleware('role:Marketing');
Route::get('/pengiriman/{nm_cust}', 'PengirimanController#getCustomer')->name('pengiriman.getCustomer')->middleware('role:Marketing');
Route::get('/pengiriman/{nm_cust}', 'PengirimanController#getNoPsn')->name('pengiriman.getNoPsn')->middleware('role:Marketing');
You don't need to call the nm_cust selector twice to get 2nd and 3rd dropdown result. As 2nd and 3rd both dropdown result depending on the num_cust selector, so you can keep both under same action. And also ensure that the AJAX URL are correct for both dropdown individually.
UPDATE:
Minimize code from your given scenario, as you have issues starting from route to controller to AJAX request. Please Follow the below steps.
Add this route in your route file.
Route::get('/pengiriman/psn-cust', 'PengirimanController#getNoPsnAndCustomer')->name('pengiriman.psn-cust')->middleware('role:Marketing');
Add this function in your controller file and don not forget to use Illuminate\Http\Request class top of your controller file.
public function getNoPsnAndCustomer(Request $request) {
$nm_id = $request->id;
$custData = Customer::orderby("nm_cust","ASC")
->select('nm_cust','alamat')
->where('nm_cust',$nm_id)
->get();
$noPsnData = Pemesanan::orderby("nm_cust","ASC")
->select('nm_cust','no_psn')
->where('nm_cust',$nm_id)
->get();
return response()->json(["nm_psn" => $noPsnData, "nm_cust" => $custData]);
}
And use this script
<script>
$(document).ready(function() {
$('#nm_cust').change(function() {
var nm_id = $(this).val();
let link = `{{ url('pengiriman/psn-cust')}}`
$('#alamat').find('option').not(':first').remove();
$('#no_psn').find('option').not(':first').remove();
$.ajax({
url: link,
type: 'GET',
data: {id: nm_id},
dataType: 'json',
success: function(response) {
if(response.nm_psn.length > 0) {
let len = response.nm_psn.length;
for (let i = 0; i < len; i++) {
let nm_cust = response.nm_psn[i].nm_cust;
let alamat = response.nm_psn[i].alamat;
let option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#alamat").append(option);
}
}
if(response.nm_cust.length > 0) {
let len = response.nm_cust.length;
for (let i = 0; i < len; i++) {
let nm_cust = response.nm_cust[i].nm_cust;
let alamat = response.nm_cust[i].alamat;
let option = "<option value='" + alamat + "'>" + alamat +
"</option>";
$("#no_psn").append(option);
}
}
}
});
})
});
</script>

str_replace inside js from Ajax call data

i want to replacement character from data loop ajax (data[i]) to some values,
i have this js
<script type="text/javascript">
$(document).ready(function() {
$('select[name="parameter"]').on('change', function() {
var idpar = $(this).val();
var subdir = $('input[name="subdirid"]').val();
var year = $('input[name="added_year"]').val();
var i = 0;
if (idpar != '') {
$.ajax({
url: "{{URL::to('myform/myformColaborate')}}/" + idpar + "/" + subdir + "/" + year,
type: "GET",
dataType: "json",
success: function (data) {
$.each(data, function (key, city2) {
$('select[name="type2"]').empty();
$('select[name="type2"]').append(
'<option disabled selected>Select Request Colaborate</option>'
);
for (var i = 0; i < data.length; i++) {
$('select[name="type2"]').append(
'<option value="'+ data[i] +'">Request Colaborate with '+ data[i] +'</option>'
);
}
});
}
});
}
});
});
</script>
and the controller
public function myformColaborate($idpar, $subdir, $year) {
$cities = DB::table("pra_kpis")
->where('subdir_colaborate','like','%'.$subdir.'%')
->where('added_year',$year)
->where('kpi_parameters_id',$idpar)
->distinct()
->pluck("subdirs_id");
return response()->json($cities, 200);
}
for example , i have script replacement outside js like this, how to define it inside js
<?php
$roles = DB::table('pra_kpis')->where('id','=',$l->id)->pluck('subdir_colaborate');
$dir2 = DB::table('subdirs')->select('name')->pluck('name');
$iddir = DB::table('subdirs')->select('id')->pluck('id');
?>
#foreach($roles as $drop)
{{$drop = str_replace($iddir, $dir2, $drop)}}
#endforeach
Try this:
Do it from front-end only,
Use data[i].replace('search string', 'replace string');

Getting the value of appended select list in jquery

I just want to ask how to get the selected value from appended select list using jquery. Please help me. Thanks in advance.
var wrapper1 = $(".column1");
array1 = ["sample1", "sample2", "sample3"];
var myRoot = window.location.origin + "/";
$.ajax({
url: myRoot + 'Payslip/GetDataFromAppend',
type: 'GET',
contentType: "application/json; charset=utf-8",
//data: JSON.stringify({ id: $this }),
async: true,
success: function (data) {
$(wrapper1).append(appendOption(data, array1[0]));
}
});
var appendOption = function (data, txtData) {
var appendfor = '<label class="col-sm-4 control-label"><label> ' + txtData + '...</label></label><div class="col-sm-7">' +
'<select class="form-control" asp-for="PayslipID" asp- items="ViewBag.PayslipID" data- val="true" data- val - required="The Payslip ID field is required." id= "PayslipID" >';
for (var i = 0; i < data.length; i++) {
console.log(data[i].value);
appendfor += '<option value="' + data[i].value + '">' + data[i].value + '</option>';
}
appendfor += '</select ></div >';
return appendfor;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group column1"></div>
The 'form-control' element is added to the page dynamically so you need to use event delegation, try this:
$(document).on('change', ".form-control", function(){
alert($(this).val())
});
'column1' should also work in place of 'document' assuming that it is a static element.

Populating select box options from previous select box value

I am getting problem while populating select box options depend on previous select box
Problem is Whenever I select the value from first select box (i.e. #city) it gives me the result of city value which is fine but as soon as I select the second value it gives me the result of second values as well as first values.
below is my code
HTML CODE
<lable>City</lable>
<select id="city" style="width:100%;text-align:left;" onchange="getSchool()"></select>
<span id='paymentform_city_errorloc' class='error'></span>
<br>
<br>
<lable>School</lable>
<select id="school" style="width:100%;">
</select>
<span id='paymentform_school_errorloc' class='error'></span>
<br>
<br>
JS CODE
var cityname, city, schoolname, schooldata, cityid, city1;
var cityarray = [];
var schoolarray = [];
function getCity() {
jQuery.ajax({
url: baseurl + "getcity.php",
async: true
, success: function (data) {
data = $.trim(data);
if (data == "false") {
console.log(data);
} else {
var myArray = jQuery.parseJSON(data);
jQuery(myArray).each(function (index, element) {
cityname = element.cityname;
cityid = element.city_id;
cityarray.push([cityname, cityid])
});
for (var i = 0; i < cityarray.length; i++) {
city1 += '<option value="' + cityarray[i][1] + '">' + cityarray[i][0] + '</option>';
}
$('#city').html("<option disabled selected></option>" + city1);
}
}
});
}
function getSchool() {
var city_id = $('#city').val();
jQuery.ajax({
url: baseurl + "getschool.php"
, data: 'cityid=' + city_id
, type: "POST"
, success: function (response) {
response = $.trim(response);
if (response == "false") {
$('#school').prop('disabled', 'disabled');
} else {
$('#school').prop('disabled', false);
console.log(response);
$('#school').append(response);
}
}
, error: function () {}
});
}
function getSchool() {
var city_id = $('#city').val();
schoolarray = []; //Add this code.
Make the above change. And your school array will reset every-time a new city is selected.

How to get data from webservice in jquery?

I have a web service with link: http://41.128.183.109:9090/api/data/getalllocations
I recived this data in dropdown using jquery .this data contains 2 objects LocationName and LocID. I want to display an alert with LocID in dropdown change function in jQuery. Here is my code:
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value?' + i + '?="">' + data[i].LocationName + '</option>');
}
}
});
});
$("#countries").change(function () {
alert();
});
Here is my HTML code :
<select tabindex="-1" class="select2_group form-control" style="display: normal; width: 290px;" name="countries" id="countries">
<optgroup label="Select Your City" id="main"></optgroup>
</select>
please try following
$(document).ready(function () {
$.ajax({
type: 'Get',
url: 'http://41.128.183.109:9090/api/data/getalllocations',
success: function (data) {
var SubDropdown = $("#main");
for (var i = 0; i < data.length; i++) {
SubDropdown.append('<option value="' + data[i].LocID + '">' + data[i].LocationName + '</option>');
}
}
});
$("#countries").change(function () {
alert($("#countries").val());
});
});

Categories

Resources