handling 2 different select option which were just appended with jquery - javascript

first thank to this question https://stackoverflow.com/questions/14792014/select-option-which-were-just-appended-with-jquery
i have another problem when option value from spilting data on sql result there are two select in one page.
Here my code
as default page
<div>
Warehouse Product
<br><input type="text" id="wh" readonly/>WHK</br>
</br>
Nomor Rak
<br><input type="text" id="posisi" readonly/></br>
Product Kategori
<br><select id="pkategori">
<option selected = "selected" value = "option1">-Kategori Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductCategory from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductCategory]'>$r[ProductCategory]</option>";
}?>
</select>
</br>
Nama Produk
<br><select id="pname">
<option selected = "selected" value="option1" >-Nama Produk-</option>
<?php
$q = mssql_query("SELECT DISTINCT ProductName from tblMstProductUHT1");
while ($r = mssql_fetch_array($q)){
echo "<option value='$r[ProductName]'>$r[ProductName]</option>";
}?>
</select>
</br>
Kode Produksi
<br><input type='text' id="pdate"></br>
Line/FM
<br><input type='text' id="line"></br>
Nomor Palet
<br><input type="text" id="pnumber"/>
</br>
Nomor Seri Produk
<br><input type='text' id="seri"></br>
Quantity(Carton)
<br><input type='text' id="quantity"></br>
<button id="save">Save</button>
<button id="edit">Edit</button>
<button id="view">View</button>
<button id="delete">Delete</button>
</div>
you see there two select option <select id="pkategori"> and <select id="pname">. Now for Edit button i call available data using ajax like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
data = msg.split("|");
//masukkan ke masing-masing textfield
var r = [data[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [data[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(data[2]);
$("#pnumber").val(data[3]);
$("#seri").val(data[4]);
$("#quantity").val(data[5]);
$("#line").val(data[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});
on url: "aksi.php", i split data using "|". According to the question that i linked in first. I succesfull append option value on <select id="pkategori"> and set this as default selected.
But when i use the same code for the second option <select id="pname"> it's caused error and data that i split doesn't show. so i stuck, what the problem?

actually your linked have the answer. in your code you just have similar var. mean on "data", it's cause conflict. Jquery will confuse to bind data,
so you just change data = msg.split("|"); to another name variable.
Your code will be like below
$("#edit").click(function(){
posisi = $("#posisi").val();
$.ajax({
type:'POST',
url: "aksi.php",
data: "op=edit&posisi="+posisi,
cache: false,
success: function(msg){
if(msg=="error"){
$(".status").html("<font color='##480000'><strong> Data tidak ditemukan..! </strong></font>");
}
else{
//karna di server pembatas setiap data adalah |
//maka kita split dan akan membentuk array
da = msg.split("|"); // it can be another variable name
//masukkan ke masing-masing textfield
var r = [da[0]];
options = [{id:0, value:r}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pkategoriOption_' + data['id'] + '" class="pkategori" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pkategori').append(option);
}
$("#pkategori .pkategori:first").prop('selected', true);
var s = [da[1]];
options = [{id:0, value:s}];
for(var i = 0; i < options.length; i++) {
var data = options[i];
var option = $('<option id="pnameOption_' + data['id'] + '" class="pname" value="' + data['value'] + '">' + data['value'] + '</option>');
$('#pname').append(option);
}
$("#pname .pname:first").prop('selected', true);
$("#pdate").val(da[2]);
$("#pnumber").val(da[3]);
$("#seri").val(da[4]);
$("#quantity").val(da[5]);
$("#line").val(da[6]);
//hilangkan status dan animasi loading
$(".status").html("");
$(".loading").hide();
}
}
});
});

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>

laravel form "select field" is not working

Hello I have a problem with "select field" when submitting the form, it tells me that the field is required even though there is already a data selected for it.
error:
When I checked the network tab, headers it is showing blank, so there is no data being passed.
network screenshot
I have already declared the year id properly inside a JS. Here's my code:
$('#tax-form').on('submit', function (e) {
e.preventDefault();
let taxdeclarationnumber = $("#tax_declaration_number").val();
let currentrpt = $("#current_rpt").val();
let year = $("#year").val();
console.log('nani poku');
$.ajax({
url: "/tax-information",
type: "POST",
data: {
tax_declaration_number: taxdeclarationnumber,
current_rpt: currentrpt,
year: year,
},
my blade:
<div class="form-group">
<label for="">For the Year</label>
<select name="year" id="year" class="custom-select year-list" data-style="btn btn-secondary">
</select>
</div>
I'm using a separate JS for this select field, this is to generate a dynamic year list.
$(document).ready(function () {
var d = new Date();
for (var i = 0; i <= 30; i++) {
// var option = "<option value=" + parseInt(d.getFullYear() + i) + ">" + parseInt(d.getFullYear() + i) + "</option>"
var option = '<option value="' + parseInt(d.getFullYear() + i) + '">' + parseInt(d.getFullYear() + i) + "</option>"
$('[id*=year]').append(option);
}
});
What other steps I need to do here? I'm pretty sure there is no issue with my controller.

Display value in dropdown based on first dropdown

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.

Pure Javascript populate data to select options from JSON URL

I had a javascript function that pulls data from url, however im having "undefined" options when im trying to add it on the next select element.
Here is my code.
First Select element
<div class="col-sm-6">
<label class="font-bold no-margins">City/State *</label>
<select name="city_state" class="form-control required" id="city_state" onchange="populateSelect(this);">
<?php
echo '<option value="'.$city_state_data->id.'">'.$city_state_data->name.'</option>';
foreach ($city_states as $city_state) {
if($city_state_data->id != $city_state->id)
{
echo '<option value="'.$city_state->id.'">'.$city_state->name.'';
}
}
?>
</select>
</div>
Second Select element
<div class="col-sm-12 col-xs-12">
<div class="form-group has-feedback">
<label class="font-bold no-margins">Locale *</label>
<select name="locale" class="form-control required" id="locale">
<?php
echo '<option value="'.$locale_data->id.'">'.$locale_data->name.'</option>';
foreach ($locales as $locale) {
if($locale_data->id != $locale->id){
echo '<option value="'.$locale->id.'">'.$locale->name.'';
}
}
?>
</select>
</div>
Now my JS script
<script>
function populateSelect(item) {
// json url
//var url = 'citystate/' + item.value + '/locales/';
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < url.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + url[i]['id'] + '">' + url[i]['name'] + '</option>';
}
}
</script>
Can you please help me how can i fix this undefined values in the select box.
Thank you.
You need to parse your JSON string if you want to access the data.
function populateSelect(item) {
var url = '[{"id":33,"name":"Boni Avenue"},{"id":34,"name":"Shaw Boulevard"}]';
var data = JSON.parse(url);
// empty select
document.getElementById('locale').options.length = 0;
var ele = document.getElementById('locale');
for (var i = 0; i < data.length; i++) {
// populate select element with json
ele.innerHTML = ele.innerHTML +
'<option value="' + data[i]['id'] + '">' + data[i]['name'] + '</option>';
}
}
Hope it helps!

How to print value and description in selected option from Ajax JSON while page loaded

I already see data is loaded on Json/Ajax. I want to add data (value and description) in selected option. I did it this way. And all data is shown on one option tab. I am lost here. Below is the Ajax code and html.
$(function(){
categoryload();
});
function categoryload() {
//var hosname =window.location.protocol + "//" + window.location.hostname + window.location.pathname;
var hosname = window.location.protocol + "//" + window.location.hostname+ "/sgw/modules/controller/categorycontroller.php";
alert (hosname);
//var ur = hosname + "/modules/controller/categorycontroller.php";
$.ajax({
url:hosname , //the page containing php script
type: "POST", //request type,
dataType: 'json',
data: '',
success:function(data){
alert(data);
var obj = data;
var areaOption = "<option value=''>Select Category </option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#category").html(areaOption);
}
});
}
HTML
<div class="form-group">
<label class="control-label col-md-4">Service Category:</label>
<div class="col-md-7">
<select class="form-control" name="category" id="category">
<option value="0">Select Category</option>
<option value="1"> </option>
<option value="2"> </option>
</select>
</div>
</div>
Categorycontroller.php
require '../service/categoryService.php';
$categoryname = #trim(stripslashes($_POST['category']));
$category = new categoryService();
$list = array();
$list[]= $category->categorylist();
$return["json"] = json_encode($list);
echo $return["json"];

Categories

Resources