Refresh selectpicker options after jQuery success is not working - javascript

I am trying to refresh a select after executing another jQuery.
I am creating firstly the select options using cURL, which produces code like this.
$json_dropdown = '[{"id":"1475471145964056","name":"Option1"},
{"id":"935675176941821","name":"Option2"},
{"id":"555309881810660","name":"Option3"},
{"id":"304608093904515","name":"Option4"}]';
Then I have the HTML that looks like htis
<h2>Delete topic</h2>
<div class="form-group">
<select class="form-control selectpicker show-tick" name="topic" id="topic_del" data-show-subtext="true" data-live-search="true" showIcon="true" data-style="btn-default" data-size="8" data-width="100%" title="Choose a TOPIC to DELETE..." required></select>
</div>
<div class="form-group">
<button type="button" class="btn btn-danger" id="delete_topic">Delete Topic</button></span>
</div>
<div id="results_del"></div>
I am loading the options into the select with this jquery
$('#topic_del').click(function(){
var a = {Topic:<?echo $json_dropdown; ?>}
$.each(a.Topic, function topics (key, value) {
$("#topic_del").append($('<option></option>').attr('data-tokens',value.id).val(value.id).html(value.name));
//$("#topic").attr('data-tokens',value.id);
});
});
Which works fine.
Then I have another script to delete an option from the select using ajax
// Delete Topic
$('#delete_topic').click(function(){
// bind 'myForm' and provide a simple callback function
$(this).prop("disabled", true);
// add spinner to button
$(this).html(
`<i class="fa fa-spinner fa-spin"></i> Deleting Topic`
);
$(this).removeClass("btn-danger");
$(this).addClass("btn-warning");
var type = $("#type").val();
var action = $("#action_del").val();
var account = $("#account").val();
var topic = $("#topic_del").val();
$.ajax({
type:'POST',
data:{ 'type': type, 'action': action, 'account': account, 'topic': topic },
url:'js/actions.php',
success: function(data){
$('#results_del').html(data);
$('#delete_topic').prop("disabled", false);
$('#delete_topic').html("Delete Topic");
$('#delete_topic').addClass("btn-danger");
$('#delete_topic').removeClass("btn-warning");
var a = {Topic:<?echo $json_dropdown; ?>}
$.each(a.Topic, function topics (key, value) {
$("#topic_del").append($('<option></option>').attr('data-tokens',value.id).val(value.id).html(value.name));
});
}
});
return false;
});
In this script, what I am trying to achieve is to refresh the options after the delete script is successful, using the same script I am using to initially create the options.
It seems I am doing something wrong, but I cannot figure out what.
UPDATE
Just realized that if I remove the selectpicker and try to remove the option that I just deleted from the select in the success like this $("#topic_del option[value='" +topic+ "']").remove(); it will work. However, if I put back the selectpicker it will not remove the option.
Could it be something with the selectpicker not allowing to do it?

I was able to achieve the functionality thanks to this thread Selectpicker with add or delete values
by adding these two lines in the success
$('.selectpicker option:selected').remove();
$('.selectpicker').selectpicker('refresh');

And one other thing. It seems that $('.selectpicker').selectpicker('refresh'); would only execute if there was any other action before that for example $('.selectpicker option:selected').remove();

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>`);
});

ajax response append to select options

In my project, I'm using laravel as a backend. My case is, when the relevant page is loaded it sends an ajax request to get vehicle data, the vehicle has vehicle model & plate number properties. I want ajax response values show in a select field. I'm using jquery ajax to do this, but it does not append the values to the select field. There is no problem in the success response. how can append these values to a select options?
My HTML :
<div class="raw">
<div class="form-group row" style="justify-content:center">
<div class="col-sm-6">
<label for="vehicleinfo">Select a Vehicle</label>
<select class="custom-select form-control" id="select_list">
<option>- Select a Vehicle -</option>
</select>
</div>
</div>
</div>
My JS:
//?show vehicles
$(document).ready(function(){
$.ajax({
type: "GET",
url: '/get_vehicles',
})
.done(function(res) {
$.each(res, function(index, value) {
$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>');
let select_option = '';
select_option += "<option value='"+ value.vehiclemodel +"'>"+ value.platenumber +"</option>";
$('#selecet_list').append(select_option);
});
})
.fail(function(err) {
console.log(err);
});
});
$('#current_vehicle_list').append('<div id="item-box"><li>' + value.vehiclemodel +" "+ '('+ value.platenumber +')'+ '</li> <button class="btn btn-sm" value='+value.platenumber+' id="removeShow"><i class="fa fa-times-circle" aria-hidden="true"></i></button></div>'); This code part is working and successfully append values to the div element. somehow it does not work for the select field.
Appreciate your help. thank you.
In order to add <option>s to your existing <select>, you can do it with one of these approaches:
Jquery standard fashion
$.each(res, function (index, value) {
$('#select_list').append($('<option/>', {
value: index,
text : value
}));
});
Jquery and pure js combination
$.each(res, function (index, value) {
$("#select_list").append(new Option("option text", "value"));
});
You have defined id of element in HTML as select_list.
But you are using id named selecet_list in your jQuery script.
That's an issue need to be resolved.

Dropdown change event not working for one option in dropdown

I am dynamically adding a select tag ,and appending option from the data comming from server and on change of the dropdown i have to put the selected data in textbox,
But if there is only one option onchange event will not work what should i do please help
My problem will be more clear by below example
var dynamicHtmlDisplay = "<input type=\"button\" Value=\"" + strAf_Manual + "\" class=\"btnAddManual\" /> </br>"
dynamicHtmlDisplay += "<select class=\"Test form-control\"><option>--</option></select>"
And after a server call i am fillin the dropdown
$('.Test').empty();
$.each(Result, function (i, p) {
$('.Test').append($('<option></option>').val(JSON.stringify(p)).html(p.Text));
});
And on change event i am entering the selected text in an textbox
$(".Test").change(function () {
var selectedObject = JSON.parse($('option:selected', this).val())
});
But if only one value is there in dropdown my change does not work is there anything else instead of onchange event ,Something like onselect event.
As you can read from the documentation for https://api.jquery.com/change/
It only works when you change the value of the dropdown, is there is only one value you didn't "change" it.
A solution is to add a blank value which is deleted after your first change call
<option value="0"></option>
<option value="1">First option</option>
$("#select1").change(function(){
// You delete the blank value for the first call
$("#select1 option[value=0]").remove();
...
Normally Dropdown change event will not fire if you select the same dropdown option.So it will not work for a single value.
Parshuram,
I assume that you are going to load select control using code behind and the below code would still work if you maintain classes and on function.
I hope this will help you. All you need is on function. Enjoy!
$(function(){
var Result = [{id:'1', value:'One'},{id:'2',value:'Two'}];
$('.Test').empty();
$.each(Result, function (i, p) {
$('.Test').append($('<option></option>').val(p.id).html(p.value));
});
$('.form-wrapper').on('change','.Test',function(){
console.log('You have selected: ' + $(this).val());
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-wrapper">
<input type="button" Value="Add Option" class="btnAddManual" /> </br>
<select class="Test form-control"><option>--</option></select>
</div>

Add new item in a select tag and refresh it without refreshing the whole page using jquery

How can I refresh a select tag after adding new item into it using Jquery.
HTML :
<select id="exam_select" class="exam_select" name="exam_select" value="Select Exam">
<option value="">Select Exam</option>
<?php
while($row=mysql_fetch_assoc($exam)):
?>
<option value="<?php echo $row['e_code'];?>"><?php echo $row['e_code'];?></option>
<?php
endwhile;
?>
</select>
<input type="text" id="add_new_deg_field" class="hide_show" placeholder="New Exam Name"/>
<button id="add_edu_deg" class="hide_show">Add</button> <p id="save_exam" class="hide_show p_hide_show"></p>
JQuery :
$.ajax({
type:'post',
url:'exam_entry.php',
data: 'add_new_deg_field='+ $('#add_new_deg_field').val(),
success: function(reply_data){
$('#save_exam').html(reply_data);
}
});
return false;
}
By this code I can save new item in my database table by clicking 'add_edu_deg' button. But can't refresh the select tag options. How can I do it using jquery. I search a lot but can't find any solution. Plz help. Thank you.
I am assuming that you want to remove the selected <option> once it has been selected since you haven't defined what you mean by refresh
If that is the case , within the success callback you can do:
$('#exam_select option:selected').remove();
If this is not your intent, the question is not clear enough
You can add an option to a select input with append.
<select><option>Option 1</option></select>
<button>Add option</button>
var x = 2;
$("button").click(function(){
$("select").append("<option>Option "+x+"</option>");
x++;
});
If you somehow save your option to x with ajax (I don't know how, never used ajax before), then execute append on your select, it will be added to the list without needing to be refreshed.
Here is a fiddle of it.
http://jsfiddle.net/8ka5Y/
$('#addOption').on('click',addOption);
var i = 0;
function addOption(){
$('#mooSelect')
.append($("<option></option>")
.attr("value",i++)
.text("Option " + i));
}
which is pretty much what is in the question
What is the best way to add options to a select from an array with jQuery?

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>

Categories