Populate list only in current row - javascript

I have dynamic add rows. Every row contains 2 dropdowns (select). They are for type and category selections. The category depends on the type.
The problem is when I change a select option, it also affects other rows, which is not my intention.
For example, when there are 3 rows. How can I improve this function so it only affects specific select options?
Here is my HTML code
<table id="dynamic_field">
<tr>
<td>
<label>Vehicle Type:</label>
<select name="vehicle_type[]" class="" id="" onchange="get_category(this.value)">
<option value="">Type</option>
<option value="Car">Car</option>
<option value="Bus">Bus</option>
</select>
</td>
<td>
<label>Vehicle Category</label>
<select name="vehicle_category[]" class="category" id="category" onchange="get_sub_category(this.value)" >
<option value="">Category</option>
</select>
</td>
<td>
<label>Vehicle Sub Category</label>
<select name="vehicle_sub_category" class="form-control subcategory">
<option value="">Sub Category</option>
</select>
</td>
</tr>
<tr>
<!--- etc. --->
</tr>
</table>
Here is my jquery code
function get_category(key){
$.ajax({
url: 'getCat',
type: "get",
data: {type:key},
success: function(data){ // What to do if we succeed
$('.category').empty();
$('.subcategory').empty();
$.each(data, function (i, d) {
$('.category').append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
}

Remove the onchange HTML attributes:
onchange="get_category(this.value)"
Instead bind the event handling via code, and find the corrsponding category/subcategory. As your related select elements are in neighboring td elements, you need to first get the row where the current select is in, and then find the other, category element:
$("[name*=vehicle_type]").change(function () {
var $type = $(this); // get the current select element
var $row = $type.closest("tr"); // find the row that has the related select elements
var $cat = $("[name*=vehicle_category]", $row); // .. the category-select
var $subcat = $("[name*=vehicle_sub_category]", $row); // .. the subcategory-select
$.ajax({
url: 'getCat',
type: "get",
data: { type: $type.val() },
success: function(data) {
$cat.empty();
$subcat.empty();
$.each(data, function (i, d) {
$cat.append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
});

I think you have to poit to te next element in the DOM, ot it will change all the DOM elements with class category. So you can use next jQuery method.
Description: Get the immediately following sibling of each element in
the set of matched elements. If a selector is provided, it retrieves
the next sibling only if it matches that selector.
Try change your code in:
function get_category(key){
$.ajax({
url: 'getCat',
type: "get",
data: {type:key},
success: function(data){ // What to do if we succeed
$(this).next('.category').empty();
$(this).next('.subcategory').empty();
$.each(data, function (i, d) {
$(this).next('.category').append($('<option>', {
value: d.id,
text : d.V_Category
}));
});
}
});
}

Related

How to show selected value using javascript in laravel

i want to show the selected value to the select option, the value actually selected but cannot show that value on select option form.
for example i have a 3 value it can be choose is anyaman, cendana, and bakulan. when 1 edit that form with value cendana, the showed value is the first sequence (anyaman) but when i open that select option that focused on the true data value (cendana).
This is HTML Script :
<div class="mb-1">
<label class="form-label" for="user-role">Asal Kelompok</label>
<select id="editkelompok_id" name="kelompok_id" class="select2 form-select">
<option disabled="" value=""> <b> Pilih asal kelompok </b></option>
#foreach($kelompok as $data)
<option value="{{$data->id}}">{{$data->nama_desa}} - {{$data->nama_kelompok}} </option>
#endforeach
</select>
</div>
The Controller
public function detaildataanggota($id)
{
$status = anggota::findOrfail($id);
return $status;
}
Java Script
<script type="text/javascript">
function detaildataanggota(id){
$.ajax({
url: "{{url('admin/pendataan/dataanggota/detail')}}" + "/" + id,
dataType: "json",
success: function(status) {
$('#editid').val(status.id);
$('#editnama_anggota').val(status.nama_anggota);
$('#editnik').val(status.nik);
$('#editjabatan').val(status.jabatan);
$('#editjenis_kelamin').val(status.jenis_kelamin);
$('#edittanggal_lahir').val(status.tanggal_lahir);
$('#editalamat').val(status.alamat);
$('#editkelompok_id').val(status.kelompok_id);
},
});
}
</script>
The problem is on #editkelompok_id
Try this
let select = $('#editkelompok_id');
select.on('change',()=>{
// Your stuff
})
or
let options = $('#editkelompok_id').children();
options.each(function() {
let option = $(this);
option.on('change', () => {
select.val(option.val());
})
})
I hope it was useful

Fetch input value after Dropdown menu item selected

I have a table about products. It has id, productdmc, productcode columns.
In this select menu, productdmc is showing.
When one item was selected, label its gonna change with related rows. Thats what i need. But i cant figure out the solution.
productcode.
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
Related input
<input type="text" name="productcode" id="productcode">
This is the js code. I dont know this is working. This is my actual problem.
<script type="text/javascript">
$(document).ready(function() {
$('select[name="productdmc"]').on('change', function() {
var tmp = $(this).val();
if(tmp) {
$.ajax({
url: '/products/create/'+tmp,
type: "GET",
dataType: "json",
success:function(data) {
$('productcode').empty();
$.each(data, function(key, value) {
$('productcode').innerHTML('<input value="'+ key +'">');
});
}
});
}else{
$('productcode').empty();
}
});
});
</script>
In my Controller:
$val = DB::table("products")->pluck("productdmc","productcode");
return json_encode($val);
I know, i messed up so much. But codes are so complicated than this. I write this code in here(shorter version). Not copy-paste. I stucked here in a while. I cant find what is the real solution is.
I am open for all kinda solution.
Sorry for my bad english.
innerHTML is a property of HTML elements, not a function of jQuery's representation.
Use html(content) instead, and I think it should work:
$('#productcode').html('<input value="'+ key +'">');
Your selector is wrong, you forgot the '#'.
var $productCode = $('#productcode');
Also, when the event 'change' is triggered, you need to fetch the selected option.
var selectedValue = $element.find('option:selected').val();
HTML
<select class="form-control" name="productdmc" id="productdmc">
<option disabled selected>DMC</option>
#foreach ($product as $products)
<option value="{{ $products->productdmc }}">{{ $products->productdmc }}</option>
#endforeach
</select>
<input type="text" name="productcode" id="productcode">
Javascript:
<script type="text/javascript">
$(document).ready(function() {
$('body').on('change', 'select[name="productdmc"]', function(e) {
var $element = $(e.currentTarget); // $(this) is also fine.
// Get selected value
var selectedValue = $element.find('option:selected').val();
var $productCode = $('#productcode');
// No value selected
if (!selectedValue) {
$productCode.val('');
return;
}
$.ajax({
url: '/products/create/' + selectedValue,
type: 'GET',
dataType: 'json',
error: function() {
$productCode.val('');
},
success: function(res) {
$productCode.val('');
if (res.length < 1) return;
$productCode.val(res[0] || '');
// This will populate more than 1 field. So,
// I'm not sure about what you expect on the backend.
// If you want to populate more than 1,
// you should change the selector/field (do not use id in this case)
// $.each(res, function(key, value) {
// $productCode.val(key);
// });
}
})
});
});
</script>
PHP
<?php
$products = DB::table('products')->get();
return response(
$products->pluck('productdmc', 'productcode')->toArray()
);
You can read more about jQuery selectors here: https://api.jquery.com/category/selectors/

Select tag change event without user interference in Jquery?

I'm having a small challenge here. I have 3 cascading drop down lists, category, subcategory, subsubcategory.The user selects a value from category list then related values show up in subcategory and when the user CHANGESthe value from subcategory related values on subsubcategory will show up. My problem is, I want to fire the change event on subcategory list without user selecting a new value! I want to simply show related values in subsubcategory when the user selects a value in CATEGORY NOT SUBCATEGORY list!
here is the code:-
<script type="text/javascript">
$('#category').change(function(){
var category_id = $(this).val();
//alert(category_id);
$.ajax({
type:"GET",
url:"/search_subcat",
data:{'category_id':category_id},
dataType: 'json',
success:function(res){
//console.log(res);
$("#subcategory").empty();
//$("#subcategory").append('<option value="0">Select</option>');
$.each(res, function(index, element) {
$("#subcategory").append('<option value="'+element.id+'">'+element.subcategory+'</option>');
})
},error:function(jqXHR, textStatus, errorThrown){
$("#subcategory").empty();
}
});
});
$('#subcategory').change(function(){
var subcategory_id = $(this).val();
var category_id = $('#category').val();
//alert(category_id);
$.ajax({
type:"GET",
url:"/search_subsub",
data:{'category_id':category_id, 'subcategory_id':subcategory_id},
dataType: 'json',
success:function(res){
//console.log(res);
$("#subsubcategory").empty();
//$("#subsubcategory").append('<option value="0">Select</option>');
$.each(res, function(index, element) {
$("#subsubcategory").append('<option value="'+element.id+'">'+element.subsubcategory+'</option>');
})
},error:function(jqXHR, textStatus, errorThrown){
$("#subsubcategory").empty();
}
});
});
It works perfect, all that I want to do is to simply fire $('#subcategory').change without user changing its value instead, I want it to fire when the user selects a category value.
Thanks
Calling change() with no arguments will trigger the event...or use trigger()
$('#subcategory').change()
Or
$('#subcategory').trigger('change')
Demo:
$('#subcategory').on('change', function() {
console.log('New value is ', this.value)
}).val(2).change()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="subcategory">
<option></option>
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>

value of an option appended to a select ends with " before the fetched value ends

I'm fetching some data using ajax from my database, the problem is when I append an option to a select with a value containing these data, the append ends the first word with " thus the rest is left outside the value tag.
Here's the empty select:
<select name="Sender" id="SenderNames" class="form-control" style="width: 100%;"></select>
This is the jQuery code:
$('#SenderSelect').on('change', function() {
$.ajax({
type: "POST",
url: 'operations/inner-operations/getNamesByService.php',
data: { action :"getService", "serviceName" : $("#SenderSelect option:selected").val() },
success: function(data) {
var responseObj = jQuery.parseJSON(data);
console.log(responseObj);
$.each(responseObj, function(i, value) {
$("#SenderNames").append('<option value='+value+'>'+value+'</option>');
});
}
});
});
The appended option should look like this:
<option value="First Second">First Second</option>
However, it is appended like this:
<option value="First" second="">First Second</option>
I just realised that I'm not closing the string properly. The append should be like this:
$("#SenderNames").append('<option value="'+value+'">'+value+'</option>');
the value tag must be wrapped by "".

How to display price of an item based on the second select box?

I have a previous question like this but it only applies to 2 select boxes so here I'm asking again if someone can help me with 3 select boxes. I have trouble displaying the price of an item based on the selection of a select box. I have 2 tables namely items and item_details. items table has columns item_id and item_name only. item_details table has columns item_details_id, item_id(fk from items table) item_size and price.
I can display the corresponding items_details on the second select box of the item based on the first select box.
HTML
<td>
<select name="item" class="form-control select2" id ="item">
<option value="0" selected="true" disabled="true">Select Item</option>
#foreach($items as $key => $i)
<option value="{!!$key!!}">{!!$i!!}</option>
#endforeach
</select>
</td>
<td>
<select name="item_details" class="form-control" id="item_details" >
</select>
</td>
<td>
<select name="price" class="form-control" id="price" >
</select>
</td>
ItemController
public function findItemDetails($id)
{
$details = DB::table("item_details")
->where("item_id",$id)
->lists("item_size","id");
return json_encode($details);
}
JS
$('select[name="item"]').on('change', function() {
var itemID = $(this).val();
if(itemID) {
$.ajax({
url: '/findItemDetails/ajax/'+itemID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="item_details"]').empty();
$.each(data, function(key, value) {
$('select[name="item_details"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="item_details"]').empty();
}
});
Routes
Route::get('findItemDetails/ajax/{id}',array('as'=>'findItemDetails',
'uses'=>'ItemController#findItemDetails'));
I provided all the information needed to make 2 select boxes function but when i tried to search for topics about dynamic boxes that involves 3 select boxes i couldn't find any. I'm new to javascript and laravel, so i tried to duplicate my first code and changed the variables if by any chance i could display the price on the 3rd box but nothing works. Heres what i have.
ItemController
public function findPrice($id)
{
$itemdetails = DB::table("itemdetails")
->lists("price","id");
return json_encode($itemdetails);
}
JS
$('select[name="item_details"]').on('change', function() {
var itemdetailsID = $(this).val();
if(itemdetailsID) {
$.ajax({
url: '/findPrice/ajax/'+itemdetailsID,
type: "GET",
dataType: "json",
success:function(data) {
$('select[name="price"]').empty();
$.each(data, function(key, value) {
$('select[name="price"]').append('<option value="'+ key +'">'+ value +'</option>');
});
},
error:function(){
}
});
}else{
$('select[name="price"]').empty();
}
});
Routes
Route::get('findPrice/ajax/{id}',array('as'=>'findPrice',
'uses'=>'ItemController#findPrice'));

Categories