how to get json data in jquery for dinamic combobox - javascript

I have json data in here
Which is obtained from the Propinsi id but I do not understand how to use json data into my combobox, my script in here... please tell me how to correct this
$(document).ready(function(){
$('#propinsi').on('change',function(){
var prop_kode = $('#propinsi').val();
console.log(prop_kode);
if (prop_kode == "") {
$('#kabupaten').prop('disabled', true);
}
else {
$('#kabupaten').prop('disabled', false);
$.ajax({
url:"<?=$url; ?>/show_kabupaten",
type:"POST",
data: {'prop_kode' : prop_kode},
dataType: 'html',
success: function(data){
$('#kabupaten').html(data);
// $.each(json, function(i, value) {
$('#kabupaten').append($('<option>').text('Pilih Kabupaten').attr('value', 'value'));
$.each( kabupaten, function( kab_nama, kab_kode ) {
alert( kabupaten.kab_nama);
});
console.log(data);
},
error: function(){
alert('error .......');
}
})
}
});
});

Something like this?
$('#propinsi').on('change', function() {
var prop_kode = $('#propinsi').val();
if (prop_kode == "") {
$('#kabupaten').prop('disabled', true);
return;
}
$('#kabupaten').prop('disabled', false);
// This is just because I don't know where to find your json data
var data = JSON.parse('{"kabupaten":[{"kab_id":"8","prop_kode":"12","kab_kode":"120‌​1","kab_nama":"KABUP‌​ATEN NIAS","kab_status":"1","kab_created_by":"1","kab_created_dat‌​e":"1496631492"},{"k‌​ab_id":"9","prop_kod‌​e":"12","kab_kode":"‌​1202","kab_nama":"KA‌​BUPATEN MANDAILING NATAL","kab_status":"1","kab_created_by":"1","kab_created_da‌​te":"1496631518"}]}');
$("#kabupaten").html("");
$.each(data.kabupaten, function(i, kab) {
var id = kab.kab_id;
var name = kab.kab_nama;
$("#kabupaten").append('<option value="' + id + '">' + name + '</option>');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="propinsi">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<br>
<select id="kabupaten"></select>
To implement it into your JS, the code below may help.
// Add this code just below the line $('#kabupaten').prop('disabled', false);
$.ajax({
url: "<?=$url; ?>/show_kabupaten",
type: "POST",
data: {'prop_kode': prop_kode},
dataType: 'json',
success: function(data) {
$("#kabupaten").html("");
$.each(data.kabupaten, function(i, kab) {
var id = kab.kab_id;
var name = kab.kab_nama;
$("#kabupaten").append('<option value="'+id+'">'+name+'</option>');
});
},
error: function() {
alert('error .......');
}
});

Related

change the select input on change of other select input

i have more than 2 divs that have 2 select inputs. when i change branch_country, the other branch_region changes according to branch_country value via ajax.
<div>
<select class="branch_country></select>
<select class="branch_region></select>
</div>
<div>
</elect class="branch_country></select>
<select class="branch_region></select>
</div>
and here is my ajax code
$('.branch_governorate_select').on('change', function(e) {
e.preventDefault();
console.log($(this).eq($(this)));
var countryID = $(this).val();
var status = $(this).parent().parent().find('.modal-body').find('#select-status-calendar')
.val();
var url = "{{ route('sett.doc_get_branch_region', ':id') }}";
url = url.replace(':id', countryID);
if (countryID) {
$.ajax({
url: url,
type: "GET",
dataType: "json",
success: function(data) {
region_input.empty();
$.each(data, function(key, value) {
region_input.append('<option value="' +
value.id + '">' + value.name + '</option>');
});
}
});
} else {
region_input.empty();
}
});
it works well, but it changes all inputs with class branch_region. but i need to change only the branch_region select input that is inside the same div

Append collected data with javascript

I have 2 different data they load based on each other id what I try to do is to append my results as row bootstrap 3 based something like:
So far I can get 3 sort of my data successfully, all the problem I
have and need help with is how to append data as described in image above?
code
javascript
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
$.each(data, function(key, value) {
$('div#dataaa').append('<div class="row"><div class="col-md-4" id="dataparent">'+value1.title+'</div><div class="col-md-8" id="datainfo">'+value.title+'</div></div>');
});
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
html
<div id="dataaa"></div>
This is how I'm getting my data now:
Update
Well I have made it work so far. Remained one issue, and that is I cannot get all my data I only can get my first result.
Changed code
<script>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$.each(result, function(key1, value1) {
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Collect data as option
var helpers = '';
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
var my_row = $('<div class="row">');
var my_html = '<div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-8"><select class="form-control" id="subs" name="subs[]">'+helpers+'</select></div>';
my_row.html(my_html);
$('div#dataaa').append(my_row);
}
});
// second data
});
}
});
}else{
$('div#dataaa').append('select set');
}
});
});
</script>
Update 2
As requested here is my first select option code
{{ Form::label('selectset', 'Select Set') }}
<select class="form-control" id="selectset" name="selectset">
<option value="">Select</option>
#foreach($selectsets as $selectset)
<option value="{{ $selectset->id }}">{{ $selectset->title }}</option>
#endforeach
</select>
change
$.each(data, function(key, value) {
helpers = '<option value="'+value.id+'">'+value.title+'</option>';
});
to
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
because on each iteration, it overwrite its previous result

How to Get Value From HTML Dropdown List using Jquery

I have dropdown list and i want to retrieve data from database when select value of downlist. This is working without having error. But this is working when i click on dropdown list, not in dropdown value. That mean work only for default value. please help me how to rectify this error. code as below.
HTML code for Dropdown list
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Jquery Code is Here
<script type="text/javascript">
$(document).ready(function () {
$("option").click(function () {
var txt = $("#lab-no:selected").val();
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>
First you need to target your select $('#lab-no') and use change event instead of click. Then you can target the selected option.
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("select option:selected").val()
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01" >Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
Try with $("#lab-no").change. This Way your event will trigger after you have made a change in the dropdown.
You should not use :selected in $("#lab-no:selected").val() since its not needed. $("#lab-no").val() will return the selected value.
Working Demo
$(document).ready(function() {
$("#lab-no").change(function() {
var txt = $("#lab-no").val();
console.log(txt)
if (txt = '') {
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {
'search': txt
},
dataType: "text",
success: function(data) {
$('#table-row').html(data);
}
});
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name="lab_no" id="lab-no" class="form-control">
<option value="Lab 01">Lab 01</option>
<option value="Lab 02">Lab 02</option>
</select>
You can use in simple way like:
var drpSelectedValue=$("#lab-no").val();
May this help for you.
You should try like this
1.You need to change jquery event
<script type="text/javascript">
$(document).ready(function () {
$("#lab-no").change(function () {
var txt = $("#lab-no").val();
alert(txt) //place alert and check value. You will get values which you have selected
if (txt == '') { //make changes here
} else {
$('#table-row').html('');
$.ajax({
url: "../svr/com-list.php",
method: "post",
data: {search: txt},
dataType: "text",
success: function (data) {
$('#table-row').html(data);
}
});
}
});
});
</script>

Dropdown in IE does not refresh in click event

I have a dropdown which has a 'click' event where I call a rest service and update the options in the dropdown using jquery, So the problem is that the options are not getting updated in IE. It works fine in chrome & others.
sample code
<select class="dropdown">
<option value="1">Column1</option>
<option value="2">Column2</option>
</select>
$(.dropdown).click(function () {
var $dropdown = $(this);
var contrId = $(this).attr('id');
var selectedVal = $(this).val();
$($dropdown).empty();
$.ajax({
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: { 'id': '10' },
}).done(function (data) {
// Clear drop down list
$($dropdown).empty();
// Fill drop down list with new data
var $option = $("<option />");
$option.attr("value", '').text('Select Column');
$($dropdown).append($option);
$(data).each(function () {
// Create option
var $option = $("<option />");
// Add value and text to option
$option.attr("value", this.Text).text(this.Value);
if (selectedVal == this.Text) {
$option.attr("selected", "selected");
}
// Add option to drop down list
$($dropdown).append($option);
});
});
});
}
Any suggestion would be helpful.
Working in I.E 9,10 and 11 tested
$(document).ready(function () {
$(".dropdown").click(function () {
var $dropdown = $(this);
var contrId = $(this).attr('id');
var selectedVal = $(this).val();
$($dropdown).empty();
$.ajax({
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: {'id': '10'},
}).done(function (data) {
// Clear drop down list
$($dropdown).empty();
// Fill drop down list with new data
var $option = $("<option />");
$option.attr("value", '').text('Select Column');
$($dropdown).append($option);
$(data).each(function () {
// Create option
var $option = $("<option />");
// Add value and text to option
$option.attr("value", this.Text).text(this.Value);
if (selectedVal == this.Text) {
$option.attr("selected", "selected");
}
// Add option to drop down list
$($dropdown).append($option);
});
});
});
});
I think the issue is IE cache requests by mistake. Add cache:false to your ajax request and probably it fix the issue by adding _={timestamp} at the end of your requests.
$.ajax({
cache:false,
url: '#Url.Content("~/FakeAPI/GETDATA")',
dataType: "json",
method: 'POST',
data: { 'id': '10' },

How to populate data from API and load into dropdown

I am working on MVC application that uses API and i want to call a method from the API so that it will load the data to the combo-box. I have no idea on how i can tackle this as am new this.
Thanks.
ClaimController function from the API which got this function.
[RoutePrefix("api/Claim")]
[Route("GetScheme")]
[HttpGet]
public HttpResponseMessage GetScheme()
{
try
{
using (IBusinessLogic logic = new BusinessLogic.Implementation.BusinessLogic())
{
Request.Headers.Clear();
var tmpresults = logic.GetScheme();
var results = (from x in tmpresults.Result select new { text = x.Description, value = x.Id }).ToArray();
var response = Newtonsoft.Json.JsonConvert.SerializeObject(results);
return Request.CreateResponse(HttpStatusCode.OK, results);
}
}
catch (Exception ex)
{
return Request.CreateResponse(HttpStatusCode.BadRequest, ex);
}
}
Views from the Client which is the UI
I want to call that function from API to load the data into the combo-box
function GetAllScheme() {
var select = $("#ddlScheme");
$.ajax({
type: "GET",
url: "http://localhost:55393/_Api/Claim",
dataType: "json",
success: function (data) {
debugger;
var datavalue = data;
var serverResponse = datavalue;
contentType: "application/json";
$.each(serverResponse, function (i, serverResponse)
{
select.append("<option value='" + serverResponse.Description + "'>" + serverResponse.Description + "</option>")
});
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
Dropdown
<select class="dropdown form-control input-xs required" id="ddlScheme" onclick="GetAllScheme()(this)">
<select
</select>
</div>
You have to append option elements into your select (dropdown) element after you get the server response. Something like this:
function GetAllScheme() {
// get the dropwdown by its id
var select = $("#ddlScheme");
$.ajax({
...
success: function (data) {
$.each(myJsonObject, function (i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description + '</td></tr>');
// for each element, add an option into the dropdown
select.append('<option>"+ mobj.Description +"</option>')
}
});
...
)}
See jsfiddle https://jsfiddle.net/n4mtj9om/
If use Chrome enter in developers tools a see how response the server put a breakpoint after server response because when use maybe
put this
function GetAllScheme() {
$.ajax({
type: "GET",
url: "http://localhost:32359/api/Claim",
dataType: "json",
success: function(data) {
$.each(data.responseJSON, function(i, mobj) {
$("#Cartbl").append('<tr><td width="50px">' + mobj.Description +
'</td></tr>');
});
},
error: function(xhr) {
alert(xhr.responseText);
}
});
}

Categories