I have cascading dropdown menus as below. I am listing selections dynamically on second and third dropdowns. While the first on change function works without problem (i am getting project list), the second on change ( $("#pro").on('change', function(e) ) simply doesn't sense any change on selection of projects. Chrome console shows no problem. What can be the problem?
<div class="form-group">
<label for="projectfamily">Proje Grubu</label>
<select class="form-control" name="projectfamily" id="projectfam">
<option value="">Seçiniz</option>
#foreach($projectfamilies as $projectfamily)
<option value= "{{$projectfamily->id}}">{{$projectfamily->projectfamily}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="project">Proje Adı</label>
<select class="form-control" name="project" id="pro">
<option value= "" disabled></option>
</select>
</div>
<div class="form-group">
<label for="version">Versiyon</label>
<select class="form-control" name="version" id="version">
<option value="" disabled></option>
</select>
</div>
JQuery
$('#projectfam').on('change', function(e) {
var projectfam = e.target.value;
$.get('/ajax_projectfamily_post?projectfam=' + projectfam, function(data){
$('#pro').empty();
$('#version').empty();
$('#pro').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger){
$('#pro').append('<option value="' + deger.id + '">' + deger.project + '</option>');
});
});
});
$("#pro").on('change', function(e) {
var project = e.target.value;
$.get('/ajax_project_post?project=' + project, function(data){
$('#version').empty();
$('#version').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger) {
$('#version').append('<option value="' + deger.id + '">' + deger.version + '</option>');
});
});
});
It appears to work as expected in chrome. See this fiddle with the ajax calls replaced. Is it a problem with the ajax call? Or perhaps an html syntax error? Check the validity of your entire HTML page. Since you only posted a fragment I can't diagnose further.
$('#projectfam').on('change', function(e) {
var projectfam = e.target.value;
var data = ['a', 'b', 'c'];
$('#pro').empty();
$('#version').empty();
$('#pro').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger){
$('#pro').append('<option value="' + data[i] + '">' + data[i] + '</option>');
});
});
$("#pro").on('change', function(e) {
var project = e.target.value;
var data = ['x', 'y', 'z'];
$('#version').empty();
$('#version').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger) {
$('#version').append('<option value="' + data[i] + '">' + data[i] + '</option>');
});
});
I would do it like this, I had a similar problem before, the onchange events need to be assigned after the elements are loaded:
$('#projectfam').on('change', function(e) {
var projectfam = e.target.value;
$.get('/ajax_projectfamily_post?projectfam=' + projectfam, function(data){
$('#pro').empty();
$('#version').empty();
$('#pro').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger){
$('#pro').append('<option value="' + deger.id + '">' + deger.project + '</option>');
});
addOnChangeThingy(); // load onclick functions
});
});
function addOnChangeThingy(){
$("#pro").on('change', function(e) {
var project = e.target.value;
$.get('/ajax_project_post?project=' + project, function(data){
$('#version').empty();
$('#version').append('<option value="' + '">' + "Seçiniz" + '</option>');
$.each(data, function(i, deger) {
$('#version').append('<option value="' + deger.id + '">' + deger.version + '</option>');
});
});
});
}
Related
I am trying to extract data from the option value. For example only ID or UserName. Can you please help?
$(document).ready(function() {
$.getJSON("http://localhost:8080/EBCargoAndCommodityServices/resources/user-form/retrieve", function(data) {
data.forEach(function(dt) {
$("#customer-list").append('<option value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
var str = this.value;
alert(str);
});
});
});
Let's say for example that dt.id = 1 and dt.contactName is Bartosz.
So you would be alerting 1Bartosz in alert(str)
While building up the options do this,
$("#customer-list").append('<option value="' + `${dt.id}_${dt.contactName}` + '">' + dt.contactName + '</option>'); // Using template literals and concatenating both id and contact name using a delimiter `_`
Then, in your change function do this.
const info = str.split('_')
/*
info will be an array with two elements
info[0] will be id i.e. 1
info[1] will be contactName i.e. Bartosz
*/
Sure you can, the best way would be to store the values you need to use into specific data attributes, then access them using the .data() method
const $ = jQuery;
$(document).ready(function() {
// Mocked data for test
const data = [{"address":"","companyName":"","contactName":"ghkkkkk","email":"","id":22,"surname":"","telephone":0},
{"address":"","companyName":"","contactName":"asdasd","email":"","id":23,"surname":"","telephone":0}]
data.forEach(function(dt) {
$("#customer-list").append('<option data-id="' + dt.id + '" data-name="' + dt.contactName + '" value="' + dt.id + dt.contactName + '">' + dt.contactName + '</option>');
});
$('#customer-list').change(function() {
const selected = $(this).find('option:selected');
$('#result').text('selected id is: ' + selected.data('id') + ' contact name is : ' + selected.data('name'))
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="customer-list">
<option>select an option</option>
</select>
<span id="result"></span>
I have this code in my javascript:
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
I need value['code'] and value2['service'] in hidden inputs so i can save them in my DB, is that possible?
update
<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();
var weight = ["{{$totalWeight}}"];
if(cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/'+weight+'/'+encodeURI(cityID),
type: "GET",
dataType: "json",
success:function(data) {
$('#des').empty();
$('#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) {
$.each(value.costs, function(key2, value2) {
$.each(value2.cost, function(key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits:0,
minimumFractionDigits:0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="'+ value3['value'] +'">'+ value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] +'</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
}else{
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
html
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo"></div> // i want my hidden input in this div
</div>
update 2
here is what i added to my ajax code and returning the result i want, but the problem is it return results like 30 times instead of only once:
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').append('<input type="hidden" value="'+code+'" name="courier" > <input type="hidden" value="'+service+'" name="courier_service" >');
});
Hope this helps.
$('select[name="postchoose"]').append('<option id="postchoose"
class="form-control" value="'+ value3['value'] +'"
code="'+value['code']+'" service="'+value2['service']+'">'+
value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number)
+' Rp' + ' - ' + value3['etd'] +'</option>');
var code=$('select[name="postchoose"] option:selected').attr('code');
var service=$('select[name="postchoose"]
option:selected').attr('service');
You can add to data attribute of option
<div id="des"></div>
<div id="calcul" class="mb-20 mt-20">
<select name="postchoose" id="" onchange="addInputHidden(this)">
<option class="form-control" value="">Select Shiping Method</option>
</select>
<div id="courierinfo">
<!--i want my hidden input in this div-->
</div>
</div>
<script >
function addInputHidden(element) {
var $option = $(element).find('option:selected'),
code = $option.data('code'),
service = $option.data('service');
if (!jQuery('#courierinfo .code_' + code).length) {
jQuery('#courierinfo').append('<input class="code code_' + code + '" name="code[]" type="hidden" value="' + code + '"><input class="service code_' + code + '" name="service[]" type="hidden" value="' + service + '">');
} else {
jQuery('#courierinfo .code.code_' + code).val(code)
jQuery('#courierinfo .service.code_' + code).val(service)
}
}
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();
var weight = ["{{$totalWeight}}"];
if (cityID) {
$.ajax({
url: '{{ url('rajaajax') }}/' + weight + '/' + encodeURI(cityID),
type: "GET",
dataType: "json",
success: function (data) {
$('#des').empty();
$('#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) {
$.each(value.costs, function (key2, value2) {
$.each(value2.cost, function (key3, value3) {
// number format
var number = value3['value'];
var nf = new Intl.NumberFormat('en-US', {
maximumFractionDigits: 0,
minimumFractionDigits: 0
});
var formattedNumber = nf.format(number);
// number format
$('select[name="postchoose"]').append('<option id="postchoose" class="form-control" value="' + value3['value'] + '" data-code="' + value['code'] + '" data-code="' + value2['service'] + '">' + value['code'] + ' - ' + value2['service'] + ' - ' + nf.format(number) + ' Rp' + ' - ' + value3['etd'] + '</option>');
// console.log(value);
// alert(value.code); // jne-pos
// alert(value2.service); //oke -reg
// alert(value3.value); // 43000 - etd 24 jam
});
});
});
}
});
} else {
$('select[name="postchoose"]').empty().append("<option value='' selected>Select</option>");
}
});
});
</script>
$('select[name="postchoose"]').on('change',function(){
var $option = $(this).find('option:selected),
code = $option.data('code'),
service = $option.data('service');
// you can use ajax to send
})
SOLVED
I added code below at the bottom of my ajax and it's working without looping results many times.
// show selected shipping information
$('select[name="postchoose"]').on('change',function(){
var selected = $(this).find('option:selected');
var code = selected.data('code');
var service = selected.data('service');
$('div#courierinfo').empty();
$('div#courierinfo').append('Shipping: <span name="courier">'+code+'</span> - <span name="courier_service">'+service+'</span><br><input type="hidden" name="courier" value="'+code+'"><input type="hidden" name="courier_service" value="'+service+'">');
});
Thanks to Bai Nguyen for the idea.
I am populating two dependent dropdown lists using an ajax call. The problem is that if I change my selection(master dropdown list) more than once, all the dependent options(the earlier values) show up in the dependent dropdown list. Here's my ajax call
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="region"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
$('[ref="sites"]').find('[name="list box element"]').append(option);
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
$('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').append(opnGrpval);
});
}
});
Change append to html then .
$.ajax({
type: "GET",
url: "index.php?r=orders/on-select",
data: {myVar: myVar},
success: function (data) {
var jdata = JSON.parse(data);
var cluster = jdata.Clusters;
var sites = jdata.Sites;
var regionOptions = '';
var dropdownOptions = ''
$.each(cluster, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
regionOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
dropdownOptions += opnGrpval;
});
$('[ref="region"]').find('[name="list box element"]').html(listoptions); $('[ref="region"]').find('.selectBoxInput').find('.dropDownBox').html(dropdownOptions);
var sitesOptions = '';
var sitesDropdownOptions = '';
$.each(sites, function (optionValue, optionLabel) {
var option = $('<option value="' + optionLabel + '">' + optionLabel + '</option>');
sitesOptions += option;
var opnGrpval = $('<li value="' + optionValue + '">' + optionLabel + '</li>');
sitesDropdownOptions += opnGrpval;
});
$('[ref="sites"]').find('[name="list box element"]').html(sitesOptions); $('[ref="sites"]').find('.selectBoxInput').find('.dropDownBox').html(sitesDropdownOptions);
}
});
I have a dropdown-menu.
JS
$.each(responseData.assignments, function(i, v) {
var assessmentId = v.assessmentId;
var assessmentType = v.assessmentType;
// Auto Populate the dropdown-menu
$('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');
});
Goal
I want to show only one HOMEWORK/COURSE_BENCHMARK, doesn't matter how many of them are there. How can I check for uniqueness in Javascript ?
You can check for length of option element with same text in that dropdown using filter function before appending new:
$.each(responseData.assignments, function(i, v) {
var assessmentId = v.assessmentId;
var assessmentType = v.assessmentType;
// Auto Populate the dropdown-menu
var optionwithsametext = $('#student-dd option').filter(function(){
return $(this).text() == assessmentType ;
})
if(!optionwithsametext.length)
$('#student-dd').append('<option value="' + assessmentId + '">' + assessmentType + '</option>');
});
There is more than one way to do this. This is an another example;
var assignments = {};
$.each(responseData.assignments, function(i, v) {
assignments[v.assessmentType] = v.assessmentId;
});
$.each(assignments, function(i, v) {
// Auto Populate the dropdown-menu
$('#student-dd').append('<option value="' + v + '">' + i + '</option>');
});
I am trying to make a select with the option value and text coming from two separate arrays (one is called like_list and the other like_list_name). The '$.each' joins two arrays and makes list of options. When I look in console.log I can see the options looking good:
$.each(like_list, function(i, item) {
console.log('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});
But when I name the output as 'optionlist' and try to put 'optionlist' into the div 'friendselect' with Inner HTML it doesn't work:
var optionlist = $.each(like_list, function(i, item) {
'<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
});
document.getElementById('friendselect').innerHTML = '[select]' + optionlist + '[/select]';
Is there anyway to get this select box into the 'friendselect' div? NOTE: i USED '[' because the side arrow wasn't working.
You should try with map function:
var optionlist = $.map(like_list, function(i, item) {
return '<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>';
}).join('');
document.getElementById('friendselect').innerHTML = '<select>' + optionlist + '</select>';
$.each() doesn't return the values in it's function, you will have to add them toghether yourself.
The best thing you can do is add the options to the select in the each loop like so:
$.each(like_list, function(i, item) {
$("#friendselect").append('<option value="' + like_list[i] + '">' + like_list_name[i] + '</option>');
});