Append a dynamic select box to a div after button click - javascript

I am trying to append an accordion div after a button click. That works fine. But inside the appended div I have a select box , that has to be dynamically populated. After getting the Json results I tried to append the option values, but it failed. When I alert, I am getting the exact results.
Here is my controller
public function getTypes(){
$types = AnsTypes::get();
return response()->json($types);
}
My Ajax
$.ajax({
url: site_base_url+ '/surveys/getquestiontypes',
type: "get",
contentType: "application/json",dataType: "json",
success: function(data){ // What to do if we succeed
if(data){
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
$.each(data, function(key, value){
'<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
}) +
'</select>'+
'</div>');
});
My response payload is:
JSON
0 {…}
answer_datatype_id 1
type_name Text
1 {…}
answer_datatype_id 2
type_name RadioButton
2 {…}
answer_datatype_id 3
type_name CheckBox
3 {…}
answer_datatype_id 4
type_name ListSingleSelection
4 {…}
answer_datatype_id 5
type_name ListMultiSelection
Response payload
[{"answer_datatype_id":1,"type_name":"Text"},{"answer_datatype_id":2,"type_name":"RadioButton"},{"answer_datatype_id":3,"type_name":"CheckBox"},{"answer_datatype_id":4,"type_name":"ListSingleSelection"},{"answer_datatype_id":5,"type_name":"ListMultiSelection"}]
My Result

this look like your $.each not return the <option> to your DOM. You can try to add the <option> to a variable called options :
let options = "";
$.each(data, function(key, value){
options +='<option value="'+value.answer_datatype_id+'">' + value.type_name + '</option>'
})
then you add your options to your DOM like this:
$(".group:last").after('<div class="group">' +
'<select class="custom-select" class="answer_datatype_id">' +
options
+
'</select>'+
'</div>');
this should work.
For the record I already tried this code and it works well, please let me know if you need something else.

Related

Add ajax return value to selectbox?

I am trying to insert a value from my database to select box using it's ID. this my code for that
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$("#brnch_name").val(segments[17].trim());
}
});
My value has returned successfully. But, it shows nothing to my select box. Can anyone help me please?
You need to add proper html to select. Something like
for(var key in obj) {
html += "<option value=" + key + ">" +obj[key] + "</option>"
}
And then $("#brnch_name").html(html).
For this example, I assume you are getting response in json format
Here is my solution:
$("#brnch_name").empty(); //clear the drop down box
for (var i=0;i<segments.length;i++)
{
html="<option value=\""+segments[i]+"\">"+segments[i]+"</option>";
$("#brnch_name").append(html);
}
You can loop the response and append to select with $('#branch_name').append($('<option>', { value: item.value, text : item.text })); here value is the value of option and text is text to be displayed on dorpdown.
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (i, item) {
$('#branch_name').append($('<option>', {
value: item.value,
text : item.text
}));
});
});
<select id="branch_name">
<option value="0">Select branch Name</option>
</select>
Use $.each like below:
$.ajax({
url : 'get_savac_member_data.php',
method : "POST",
data : data,
success : function(response){
// window.location.replace("items_insert_form.php");
var res = response;
var segments = response.split(",");
$.each(res, function (key, value) {
$("#brnch_name").append($("<option></option>").val(segments[key].trim());
});
}
});
You need to iterate through each branch names from response and append the same as individual <option> tags. However you have already got several solutions for the same, while mine uses simple string replace.
/* this is only relevant script */
var response = 'Branch 1,Branch 2,Branch 3,Branch 4';
$('<option>' + response.replace(/\,/g, '</option><option>') + '</option>').appendTo('#branch_name');
/*in-case you wish to show a default selection */
$('#branch_name').prop('selectedIndex', 3);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="branch_name"><option value="0">Select branch Name</option></select>

Populating JSON array to drop down reserved word column name conflict

This is the first time ill use JSON. I used the json_encode(myarrayhere) to return array value as shown below.
There is a corresponding value on change of selected value on dropdown.
I verified that I get the array data by using alert(dataArray) and it returns like this
[{"title":"First"},
{"title":"Second"},
{"title":"Third"} ]
I used the word title as column name for a table I'm using in my database.
But the problem now is how to properly populate them in a drop down. I tried to do value.title but it looks like that title is a reserved word/method in php
$.ajax({
type: 'POST',
data: {ctgy: selected},
url: 'awts.php' ,
datatype: 'json',
success: function (dataArray) {
alert(dataArray);
var items = '';
$.each(result,function(name,value) {
items += "<option value='"+value.title+"'>"+value.title)+"</option>";
});
$("#dropdownselectid").html(items);
}
});
Thanks in advance.
Firstly, if you check the console you'll see that you have a syntax error. You have an extra ) when you append value.title to the HTML string.
Secondly, your $.each() call is attempting to loop through result when your data is in a variable named dataArray.
Try this:
$.ajax({
type: 'POST',
data: { ctgy: selected },
url: 'awts.php',
datatype: 'json',
success: function(dataArray) {
var items = '';
$.each(dataArray, function(name, value) {
items += '<option value="' + value.title + '">' + value.title + '</option>';
});
$("#dropdownselectid").html(items);
}
});
Working example

how to append a html tag from an ajax call response

I have an ajax function :
$('#app-name').change(function () {//1
console.log("inside change");
var applname= this.value;
console.log(applname);
$.ajax({//2
url: 'foo',
method : 'GET',
dataType : "json",
contentType: "application/json",
data: {"AppID":"appname"},
success: function(data){
var order_data = data;
$('#foo-name').html('');
$.each(order_data, function(i, item) {//3
console.log(order_data[i]);
$('<option value='+ order_data[i] +'>'+order_data[i]).html('</options>').appendTo('#foo-name');
});//3
}
});//2
});//1
This function is doing everything else except appending value to the html.
Am i doing it wrong? Can you help solve this issues.
Place the closing </option tag in the jQuery object you create. Don't set it through the html() method. Try this:
$('<option value="' + order_data[i] + '">' + order_data[i] + '</option>').appendTo('#foo-name');
That said, you can also improve performance of your code by building the string in the loop and appending it to the select once, like this:
success: function(data) {
var options = '';
$.each(data.split(/\n/), function(i, item) {
options += '<option value=' + item.trim() + '>' + item.trim() + '</option>');
});
$('#foo-name').html(options);
}
Update You also need to split() the text you state that you're returning before looping through it.
Please use below code in your ajax success event.
success: function(data) {
var _html = '';
$.each(order_data, function(i, item) {
_html += '<option value='+ item +'>'+item+'</options>';
});
$('#foo-name').append(_html);
}

Select combo box dynamically in jquery mobile

I want to append value from data base on option tag combo box. But when I first doing option tag's value empty and then I appending through AJAX then it only showing one value. But I want like all option should be visible but one should selected automatically.
my code
$('#b').on("click", "a", function () {
var patid= $(this).attr('id');
$.ajax({
type:"GET",
url:"https://localhost/patient_details1.php?patid="+patid,
dataType:'JSON',
success:function(response)
{
("#pat_type").html("");
for (var i=0;i<response.length;i++)
{
$('<option value="'+ response[i].pattype +'">'+
response[i].pattype +'</option>').appendTo("#pat_type");
}
}
}
});
});
use $('#pat_type').empty().
check when you get data from your request. You need to get it
only after loading your page.
You having typo error ("#pat_type").html("");
make it $("#pat_type").html(""); or $('#pat_type').empty();
for (var i = 0; i < response.length; i++){
listItems+= "<option value='" + response[i].pattype + "'>" + response[i].pattype + "</option>";
}
$("#pat_type").append(listItems);
// for setting selected item based on value
$('#pat_type').val('selectedvalue');

Issue filling select box via ajax call in Django

I am running into an issue creating cascading select boxes (backend Django-though I think this portion is mostly worked out). I have the following javascript code adapted from this stackoverflow response.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(){
$('select[name=measurement_a]').append('<option value="' + this.key + '">' + this.value +'</option>');
// $('select[name=measurement_a]').append($("<option />").val(this.key).text(this.value))
});
},
return: false
})
})
});
In my project I select an experiment which triggers a call to "get_measurements" function and receive a list of "measurements" which should populate the measurement select box. Currently when I select the experiment I see the json response as expected:
{1: "MyFirstMeasurment", 2: "MySecondMeasurement"}
The measurement select box received 2 new selections however, both of them have the text "undefined" as opposed to "MyFirstMeasurement" and "MySecondMeasurement". I am guessing this is something simple in my code, Thank you for the help, let me know if you need more information.
It turns out I needed to do a couple of things to fix this, thanks for the help and hints. Here is the final code.
$(document).ready(function(){
$('select[name=experiment]').change(function(){
experiment_id = $(this).val();
request_url = '/admin/get_measurements/' + experiment_id + '/';
$.ajax({
url: request_url,
success: function(data){
$.each(data, function(key, value){
$('select[name=measurement_a]').append("<option value='" + value + "'>" + value +</option>");
});
},
return: false
})
})
});

Categories

Resources