Jquery Chosen Ajax call not rendering the options - javascript

I am using Jquery 1.6.4 and chosen 1.4.1. I am facing issue while rendering the options from AJAX. Following is my code.
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery(".chzn").data("placeholder","Select Frameworks...").chosen();
jQuery("#item").chosen().change(function(e, params){
values = jQuery("#item").chosen().val();
$('#item_selected').val(values);
});
});
$('#customer').click(function() {
var url = "ajax_common.php?action=getItem&companyid=1";
$.ajax({
type: 'GET',
url: url,
dataType: 'html',
success: function(data){
$("#item option").remove();
$("#item").append(data);
$("#item").trigger("liszt:updated");
}
});
</script>
<select class="chzn inpt-fld" multiple="true" name="item" id="item" style="width: 96%">
</select>
But the value is not appending in the multi-select drop-down?

The problem seem came from the way you output ajax response. You can not append options in the select tag dynamically because it is not belong to the current select. Meaning this select can not detect the options that previously not exist (as hard code).
You should include select and option together in ajax_common.php and render in div as innerHtml.
// inside ajax_commond.php :
<select class="chzn inpt-fld" multiple="true" name="item" style="width: 96%">
<option> xxxx </option>
</select>
// render the ajax response in :
<div id="item"></div>

Related

bootstrap-select doesn't populate from AJAX call

I am trying to populate a bootstrap-select control using the following AJAX call:
function loadCategories() {
$.ajax({
url: '../handlers/getcategorylist.ashx',
data: null,
method: 'post',
dataType: 'json',
success: function (data) {
alert(JSON.stringify(data));
$('#ddlCategories').html(JSON.stringify(data));
$('#ddlCategories').selectpicker('refresh');
},
error: function (e) {
console.log(e.responseText);
}
});
}
The HTML for the bootstrap-select is as follows:
<div class="row mb-2">
<div class="col-lg-10 offset-lg-1">
<select id="ddlCategories" name="ddlCategories" data-width="25%" class="form-control selectpicker">
<option value="select">Select From The List</option>
</select>
</div>
</div>
The AJAX call executes and is successful. Using JSON.stringify() I get the following data back (shown in an alert):
For whatever reason, the bootstrap-select doesn't populate. It displays empty. What am I missing here?
Hi it seems like you're setting the inner HTML of your select element to a array of objects. You probably have to .forEach() through all the objects inside of your response array and append them to the select element (like described in the following StackOverflow answer. If you'd also like to remove existing content from the select element consider setting the html to blank.
So something along the lines of:
data.forEach(entry => {
$('#ddlCategories').append(`<option value=${entry['ID']}> ${entry['Name']} </option>`);
});

select2 not letting my other scripts work

Sir, my ajax isnt loading when i use select2 plugin .
it works fine when i remove it. the blur event is working.
but i want to be able to search in the dropdown, and somehow ajax isnt working
this part isnt working
$("#bank_id").focus();
so due to above script not working the blur event in the code below isnt working.
this is the script and html
<div class="col-md-6">
<div class="form-group">
<label>Bank<span><font color="red"></font></span></label>
<select class="form-control select2" name="bank_id" id="bank_id">
<c:choose>
<c:when test="${bankDetailsEdit.bank_id != 0}">
<option value="${bankDetailsEdit.bank_id }" >${bankDetailsEdit.bankName }</option>
</c:when>
<c:when test="${bankDetailsEdit.bank_id == 0}">
<option disabled selected>Select Bank</option>
</c:when>
</c:choose>
<c:forEach var="bank" items="${bankMasterDetails}">
<option value="${bank.bank_id}">${bank.bank_name}</option>
</c:forEach>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<label>Bank Branch Name<span><font color="red"> </font></span></label>
<select class="form-control select2" name="bankBranchId" id="op1" >
<option value="${bankDetailsEdit.bankBranchId }" >${bankDetailsEdit.bankBranchName }</option>
<c:forEach begin="0" end="100" varStatus="loop">
<option></option>
</c:forEach>
</select>
</div>
</div>
<script>
$('.select2').select2();
$(document).ready(function(){ /* PREPARE THE SCRIPT */
$("#bank_id").focus();
$("#bank_id").on('blur change',function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var bank_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'bank_id':bank_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/bankBranchDetails",
data : ({
'bank_id':bank_id
}),
success: function (bankList) {
$('#op1').empty();
var opt = '<option disabled selected>Select Branch</option>';
for (var i = 0; i < bankList.length; i++) {
$('#op1').append(opt);
opt = new Option(bankList[i].bank_branch_name,bankList[i].bank_branch_id);
}
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
$("#op1").change(function(){ /* WHEN YOU CHANGE AND SELECT FROM THE SELECT FIELD */
var branch_id = $(this).val(); /* GET THE VALUE OF THE SELECTED DATA */
var dataString={'branch_id':branch_id}; /* STORE THAT TO A DATA STRING */
$.ajax({
type: "GET",
url: "${pageContext.request.contextPath}/broker/branchIfscDetails",
data : ({
'branch_id':branch_id
}),
success: function (data) {
var ifsc = data;
document.getElementById("ifsc").value=ifsc;
},
error: function (request, error) {
alert("Unable to fetch bank details");
}
});
});
});
</script>
From this page: https://select2.org/programmatic-control/events:
Select2 has an internal event system that works independently of the
DOM event system, allowing adapters to communicate with each other.
You are tied to using the plugins event handling mechanism so the first paremeter of the jQuery on function needs to be changed.
from $("#bank_id").on('blur change',function(){
to $("#bank_id").on('select2:select',function(){
Unfortunately $("#bank_id").focus(); will not work because it is not listed in the available select2 events.
You're success callback function in the first event listener, which tries to generate options element for the 2nd select box will also not work as select2 has a different way of adding options dynamically through AJAX as listed in this page: https://select2.org/data-sources/ajax
You need to use $('#bank_id').select2('open'); instead of $("#bank_id").focus(); to open the bank selection on page load.
You can check their documentation.

HTML control functionalities

I have a select html element
like this:
<select>
<option id="US" value="US">
</option>
<option id="Canada" value="Canada">
</option>
</select>
I want two things:
I want to post request to server on selection of option
And I want to put html elements inside option
Are these two things possible (for all browsers, especially modern browser)?
Use change event on select.
$('select').on('change', function() {
$.ajax({
url: '',
data: {
...
}
});
});
Embedding HTML inside option.NOT RECOMMENDED
$('option:first').html('<div>Hello</div>');
If you are using jquery :
$(function() {
$('select').on('change', function() {
$.post('your/path', $(this).val(), function(data) {
var option = $('select option[value="'+$('select').val()+'"]');
// Do what you want with your option
};
});
});

How do you submit the selected value in a dropdown via ajax in Django

Am a little bit newbie to django ajax so my question might be an easy thing for experts.
I have a select option dropdown where i want when the user selects a value from dropdown, the value is submitted via ajax so that i can run querysets in the django backend using the selected value.
I can somehow figure out to do this in the backend but need a little help with how to submit this value in the front end by ajax.
here is the dropdown code,just basic html,
<select>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
I want an ajax function that will send the selected value to server so that i can use it to run a queryset in the django backend and return the result to ajax success function appropriately.
Thanks in adavnce
Here's an example using JQuery that places an event handler on the select widget that will call your Django view when the user makes a selection. In this example the selected name is being appended to the URL so that Django can grab it with the following regex in urls.py:
url(r'^path_to_app/(?P<name>\w+)$', 'app.views.function'),
Here's an example:
<select id="chooseme">
<option>--select a name--</option>
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function() {
$('#chooseme').change(function(){
var name = document.getElementById("chooseme").value;
$.get('/path_to_app/' + name, function(data){
// do something here with a return value data, if desired
});
});
});
</script>
Check that:
<select id="select_form">
<option>joshua</option>
<option>peter</option>
<option>james</option>
<option>pawine</option>
<option>flonah</option>
</select>
var name = $('#select_form').find(":selected").text();
var url = 'your_url_here'+userName+'/';
$.get(url, function(data)
{
//do something with data
})
I tried like this for the following select dropdown:
<select id="select_dropdown">
<option value='joshua'>joshua</option>
<option value='peter'>peter</option>
....
....
</select>
<script>
$(document).ready(function(){
$('#select_dropdown').change(function(){
var e = document.getElementById("select_dropdown");
var value = e.options[e.selectedIndex].value;
$.ajax({
url: "your-url",
type: "post",
data: value,
success: function(data) {
console.log(data);
}});
});
</script>

Put data into textboxes when item is selected in combobox

I have a combobox with a name and ID of "device". When a device is selected from the combobox e.g. "iPhone 1st Gen", I want a text field with a name and ID of "processor" to fill with the processor name e.g. "Underclocked 412Mhz".
How can I do this?
I can use HTML, PHP and Javascript.
You can do this using Ajax. The most easy way is making the AJAX request with jQuery.
Below an example:
Call a JavaScript function when the 'change' event ocurred on your combobox:
<select id="device" onchange="changeDevice(this.id);">[your options]</select>
Make an ajax request in your JavaScript method:
function changeDevice(deviceID){
$.ajax({
type:'post',
url:'[url of your php file]',
dataType:'text',
data:{device_id:deviceID},
success:function(response){
//assign the text response to your input text
$('#processor').val(response);
}
});}
You could fix this with plain old Javascript
<select name="combo">
<option value="dog">Dog</option>
<option value="cat">Cat</option>
<option value="Duck">Duck</option>
<option value="Rabbit">Rabbit</option>
</select>
<input type="text" name="picked" id="picked">
<script>
document.getElementsByName('combo').item(0).onchange = function(){
document.getElementsByName('picked').item(0).value = document.getElementsByName('combo').item(0).value;
}
</script>

Categories