ajax response append to select options - javascript

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.

Related

How to update a dropdown list dynamically using JQuery?

I have a dropdown list which is initially empty:
<div>
<label>Boarding Point </label>
<select title="Select pickup city" id="boardingDropdown">
</select>
</div>
I want to update it from the json data obtained from an API.
I can print the data obtained from API in the console, but I cannot
add it to the dropdown using jquery.
here is my jquery code
$.getJSON(busApi, function(boardingPoints) {
$.each(boardingPoints, function(index, value){
let $boardingOption = $("<option>" + value + "</option>");
$("#boardingDropdown").append($boardingOption);
});
});
The dropdown just shows undefined without any other data.
I have tried other similar questions (like this and this) but they did not solve my problem.
Could somebody tell me what am I doing wrong?
Thanks.
Edit:
console.log(value) shows the output
Kathmadnu
Birgunj
Pokhariya
Langadi Chowk
Bhiswa
Birgunj
which is the expected output from the api.
I created a list with this data
let buses=["Kathmadnu",
"Birgunj",
"Pokhariya",
"Langadi Chowk",
"Bhiswa",
"Birgunj"
];
Now the list still show undefined initially, but if I click on it, it shows the dropdown list as expected.
Does it mean there is problem with the API? But I can see the data obtained from the API in the console?
Try this solution:
$.each(items, function (i, value) {
$('#boardingDropdown').append($('<option>', {
value: value_value,
text : text_value
}));
});
The output should be something like this:
<select title="Select pickup city" id="boardingDropdown">
<option value="value_value">text_value</option>
</select>
Instead of:
let $boardingOption = $("<option>" + value + "</option>");
you should use:
let boardingOption= "<option>" + value + "</option>";
And in your code:
$(#boardingDropdown").append($boardingOption);
you missed a quote mark, it should be: $("#boardingDropdown")
Finally, according to my corrections, it should become:
$("#boardingDropdown").append(boardingOption);
Found the problem:
I had given id to the <select> tag and was adding the options to this tag.
<select title="Select pickup city" id="boardingDropdown">
</select>
Instead, what I did was to create a <div> tag above the <select> tag, and append <select>, then <option> and then </select> from the jquery.
<div>
<label>Boarding Point </label>
<div id="boardingDropdown"></div>
</div>
Then in the jquery, I appended the <select> tag as well:
$.getJSON(busApi, function (boardingPoints) {
let opt = '<select>';
$.each(boardingPoints, function (index, value){
opt += '<option value="' + index + '">' + value + '</option>';
});
opt += '</select';
$("#boardingDropdown").append(opt);
});
Now it is working as expected. :)

Refresh selectpicker options after jQuery success is not working

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();

Having problem with Select append() in ajax

All the code works will. When I put console.log(value.rental_id), all the rental_id pop out in the console, meaning I suspect the problem is in the append code, but I have tried a lot of methods, till can't fix it.
The json data is coming out too, working fine
Appreciate your help
$(document).ready(function() {
var url = "rental_id_json.php";
$.getJSON(url, function(data) {
$.each(data, function(index, value) {
// APPEND OR INSERT DATA TO SELECT ELEMENT.
console.log(value.rental_id);
$('#rental_id').append('<option value="' + value.rental_id + '">' + value.rental_id + '</option>');
});
});
});
<select type="text" name="rental_id" id="rental_id" class="input">
<option value="-" selected>Rental ID</option>
</select>
enter image description here

How to pass database value to a dynamically added dropdown field

I have a page called new_booking.php and a page called addmore.php, i required the addmore.php inside the new_booking.php,When i click on the add more button it adds a dynamic drop down field. here snapshot of my code
</DIV>
<SCRIPT>
function addMore() {
$("<DIV>").load("addmore.php", function() {
$("#product").append($(this).html());
});
}
function deleteRow() {
$('DIV.product-item').each(function(index, item){
jQuery(':checkbox', this).each(function () {
if ($(this).is(':checked')) {
$(item).remove();
}
});
});
}
</SCRIPT>
Now the problem is when i click on the add more button it just add a text field without the value from database in a drop down.here is a snapshot of my addmore.php code
<DIV class="product-item float-clear" style="clear:both;"> <DIV class="float-left"><input type="checkbox" name="item_index[]" /></DIV>
<DIV > <select class = "mdl-textfield__input" id="categories" name="roomtype[]" >
<option value="">Choose Room Type</option>
<?php
$resultUser = mysqli_query($conn, "SELECT * FROM room_type ");
//$NoRowStaff = mysqli_num_rows($resultStaff);
if ($resultUser->num_rows > 0)
// Loop through the query results, outputing the options one by one
while($row = $resultUser->fetch_assoc()) {
echo '<option value="'.$row['rt_id'].'">'.$row['type'].'</option>';
}
?>
</select></DIV> <br><br>
<DIV> <select class = "mdl-textfield__input" name="roomno" id="subcat" required>
<option value="" selected>Choose Room number.... </option> </select></DIV>
</DIV>
How do i get to Append the value from the database to the newly added drop-down field, so that anytime i click on the addmore button it comes with value from database?
The way you are trying to complete this task will not work..because as far as i can understand your code, you are trying to call a php function within a javascript function.
What you can do is to implement a ajax function.
https://www.w3schools.com/xml/ajax_intro.asp
the process will look like this:
1. An event occurs in a web page (a button is clicked)
2. The Ajax object sends a request to a web server
3. The server processes the request (like get value from database)
4. The server sends a response back to the web page
6. The response is read by JavaScript
and after this you can append this value dynamically to your options :)
As Requested per Comment a simple Demo
http://crisscrosscrass.epizy.com/ajaxexample.php
code ajaxexample.php
<body>
<div id="" class="App-header">
<h1>This is an AJAX Example</h1>
<button onClick="addMore()">Add more </button>
<div id="output">
<div>
</div>
<script>
function addMore(){
$.ajax({
type: "POST",
url: "addmore.php",
// data: data, <--- in case you want also send some data to the server like Username etc.
success: function(data) {
$("#output").append(data);
},
error: function(){
// will fire when timeout is reached
$("#output").html("<h1>connection to the server failed!</h1>");
},
timeout: 1200
});
}
</script>
</body>
code addmore.php
<?php
//here you need to put you function for calling the database and return the values that you need
echo "Calling DatabaseRandom Value " . (rand() . "<br>");
?>

Use a variable created using javascript in HTML

Using JavaScript I get the selected value of this select:
<select class="form-control pull-right" name="Type" id="Type" tabindex="" >
<option>-Type-</option>
<option value="1">Re</option>
<option value="2">Cre</option>
<option value="3">Ca</option>
</select>
var drop = document.getElementById("Type")
alert(drop.value)
I want use the variable gotten by JavaScript in the same HTML file. How can I do it?
In HTML I want something like this:
<div class="col-xs-12 col-sm-3 col-md-3">
{{.TYPE.Account_Number}}
</div>
so that while displaying Account number is dynamic depending on the selected value
I'm not sure what you are trying to do but here is a start point for you.
Use some jQuery events to hook the user actions to the code - in this case I would use change() event to display the selected value dynamically on the page.
Here is a sample code and demo:
JSnippet Demo
$('#Type').change(function(){
//Get selected value:
var selectedValue = $(this).val();
var selectedText = $(this).children(":selected").text();
//Set result:
$('div').text(
"Type Value:" + selectedValue +
" Type name:" + selectedText
);
});

Categories