Select2 Change Event - Change the options for next select2 box on first select2 box value change - javascript

I have 2 select2 boxes. First is Category and next is Sub-category.
Now, I want to change the options for subcategory box based on Category box selected value. And the data for Subcategory box should load using AJAX.
Please help me.

just solved it myself
<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/css/select2.min.css" rel="stylesheet" />
<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.0/js/select2.min.js"></script>
<select class="js-data-example-ajax" id="category" >
<option value="">Select a category</option>
<option>cat1</option>
<option>cat2</option>
<option>cat3</option>
</select>
<select class="js-data-example-ajax" id="sub-category" >
</select>
<script>
$("#category").select2({
placeholder: "Select a category",allowClear: true
});
$("#sub-category").select2({
placeholder: "Select sub-category",allowClear: true
});
$('#category').on("change", function (e) {
var result = '';
var catval = $(this).val();
if(catval != '') {
url = "subcats_top/"+ catval;
$.ajax({
type: "GET",
url: url,
dataType: 'json',
success: function(data){
var length = data.length;
if(length > 0) {
for(key in data) {
result += '<option value="' + data[key].id + '">' + data[key].name + '</option>';
}
} else {
}
$("#sub-category").html(result);
}
});
}
});
</script>

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

how to get json data in jquery for dinamic combobox

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 .......');
}
});

default select not displayed in dropdown

This is dynamically loaded dropdown box from a php file. I have put a default option Select Language But this is not displaying once the ajax elements loaded.
How can I make the select language as default even after the ajax items are loaded?
<select id="name">
<option style="display:none;" selected>Select language</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
$el.empty() statement removes all the options from the select. You shouldn't remove the first option.
For this, use not method and :first pseudo-class in order to keep the default option.
$el.find('option').not(':first').remove();
Because you need to remove old options, and add new ones without loosing the default "Select language" text, you can do like this:
<select id="name">
<option style="display:none;" selected>Select language</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
//adding your default value
$el.append('<option selected>Select language value</option>');
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>

get the multiple checked value from select tag using multiple="true"

<Select id="chkProduct" multiple="true">
</select>
<script type="text/javascript">
$(function () {
$(document).ready(function() {
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: 'http://###.##.##.##/####/Country.svc/ProductBind',
data: '{}',
dataType: "json",
processData: false,
success: function (data) {
var oi;
for (var i = 0; i < data.Data.length; i++) {
appendString = "<option value='"+data.Data[i].Product+"'>"+data.Data[i].Product +"</option>";
$("#chkProduct").append(appendString);
}
},
error: function (result) {
alert("Error");
}
});
});
});
</script>
i need some suggestion how can i get the checked value after binding the data..
this dropdown bind checkbox with default OK AND CANCLE button and on OK cleck i get single checked value instead if multiple checked value...
it allow to select multiple check but it take single checked item value...and i want multiple checked value
For a multiple select, the .val() returns an array of the selected values (not text). Here is an example:
Given an empty select and a button we'll click to get the selected values
<select name="chkProduct" id="chkProduct" multiple="true" data-native-menu="false">
</select>
<button id="btnGet">Get Selected</button>
The script loads some options on pagecreate (this would be your ajax function) and then the click handler displays the selected values as a comma delimited list:
$(document).on("pagecreate", "#page1", function(){
var appendString = '';
for (var i = 0; i < 6; i++) {
appendString += "<option value='"+ i +"'>item "+ i +"</option>";
}
$("#chkProduct").empty().append(appendString).selectmenu( "refresh" );
$("#btnGet").on("click", function(){
alert($("#chkProduct").val());
});
});
Here is a working jsFiddle

Add values to select field dynamically

I am trying to add values to a select field dynamically if there not listed. I have dynamic fields generated through jquery. I am populating these select field values through mysql fetch query from table courses_selection_list. Each select field generated has three options. I have a hidden div show only if option Other – Not listed is selected. The input in the hidden div shows a unique id number value I pull from an ajax call. I am now having difficulties trying to increment the value by one every time Other – Not listed is selected in different select fields. How can I increment this intial value by one? DEMO or Fiddle
<script">
$(document).ready(function () {
$('select').change(function() {
var option = $(this).val();
showFields(option);
return false;
});
var $increment_num = $('#course_increment_num');
var interval = 1000; //3000 = 3 seconds
function getCourseId() {
$.ajax({
type: 'POST',
url: 'courseAutoIncrement.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
var $cloned = $('#course_catalog');
var num = parseInt(data);
$increment_num.val(num);
$cloned.each(function(i){
var $this = $(this);
$this.find('[name^="new_course_"]').first().val(num+i);
})
},
complete: function (data) {
// Schedule the next
setTimeout(getCourseId, interval);
}
});
}
setTimeout(getCourseId, interval);
function showFields(option){
var content = '';
for (var i = 1; i <= option; i++){
content += '<div id="course_'+i+'"><label>Course # '+i+'</label><br /><label>Course Name:</label> <select id="coursename_'+i+'" name="coursename_'+i+'" class="course_list"><option value="" >--- Select ---</option>"'
<?php
$course_query = $db_con->prepare("SELECT course_id, course_name FROM courses_selection_list ");
$course_query->execute();
$data = $course_query->fetchAll();
foreach ($data as $row){
//dropdown values pulled from database
echo 'content += \'<option value="' . $row['course_id'] .'">' . $row['course_name'] . '</option>\';';
}
?>
'"';
content += '</select><div class="hideNewCourse" style="display:none;">Course ID<input type="text" id="new_course_'+i+'" name="new_course_'+i+'"/><label for="newCourse_'+i+'">Add Course Name to List:</label><input type="text" id="newCourse_'+i+'" name="newCourse_'+i+'"/></div></div>';
}
$(document).on('change', "[id^=coursename_]", function () {
var $this = $(this);
if ($this.val() == "3") {
$(this).closest('div').find(".hideNewCourse").show();
} else {
$(this).closest('div').find(".hideNewCourse").hide();
}
});
$('#course_catalog').html(content);
}
});
</script>
HTML
Increment By: <input type="text" id="course_increment_num" value="" readonly></br>
<strong>How many courses offered?</strong>
<select name="courses_offered" id="courses_offered">
<option value="default">---Select---</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<div id="course_catalog"></div>
This should do it:
...
$('#course_catalog').html(content);
$('#course_catalog').find('[id^=coursename_]').on('change', function(){
var $this = $(this);
if($this.val() == 3){
$('input[id^=new_course_]').each(function(index){
var start = parseInt($('#course_increment_num').val(), 10);
$(this).val(start+index);
})
}
});
You will also need to run that .each loop in your ajax success callback to ensure that the id is up to date
You can store the value in a global variable in javascript and increment it every time Other - Not Listed is selected. Like this:
var globalValue = 0;
$(document).on('change', "[id^=coursename_]", function () {
var $this = $(this);
if ($this.val() == "3") {
globalValue++;
$(this).closest('div').find(".hideNewCourse").show();
} else {
$(this).closest('div').find(".hideNewCourse").hide();
}
});

Categories