I want to display data in select box option from ajax response.
here is my view file
<select class="form-control" name="vendor" id="vendor_list" required style="width: 159px;">
<option value="">Vendor 1</option>
</select>
Here is my ajax success function
success: function(data) {
$.each(data, function(i, value) {
console.log(value);
$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
console.log(value);
});
}
here is my ajax response json data
[{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]
How to display value in select box.
giv me suggestion.thanks
I think the problem is with
$('#vendor_list').append('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
It will be much better if you create a option string & append it after entire data has been iterated
Since it is not possible to replicate the ajax , so I have directly use the ajax response
You can put the entire code inside success block , but you will not need var x because data will play role of var x=[...] in your case
var x = [{"vendor_name":"scscss"},{"vendor_name":"xzcdsfdx"}]
var _options =""
$.each(x, function(i, value) {
_options +=('<option value="'+ value.id+'">'+ value.vendor_name +'</option>');
});
$('#vendor_list').append(_options);
Check this jsFiddle
Related
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. :)
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
I my form I have few dropdowns chained between them with AJAX.
This is how I a populating them
function getleaseterm() {
//get a reference to the select element
$select = $('#id_leaseterm');
//request the JSON data and parse into the select element
var l_id = ($("select[name='lease'] option:selected").attr('value'));
//var l_id = 13;
l_url = "/api/get_leaseterm/"+l_id+"/";
$.ajax({
url: l_url,
dataType:'JSON',
success:function(data1){
//clear the current content of the select
$select.empty();
$select.append('<option value="-1">Select term </option>');
//iterate over the data and append a select option
$.each(data1, function(key, val){
$select.append('<option value="' + val.id + '">' + val.as_char + '</option>');
})
},
});
}
And this is the control
<select class="select" id="id_leaseterm" name="leaseterm">
<option value="-1" selected="selected">-----</option>
</select>
It all works , I am changing values in my dropdowns and options of other dropdowns are updated.So I can select the relevant value.
The problem is when I Save the for - the form gets not the value that I have put there but the default value that was there before any manipulation of Ajax have been done.
Also when I do view source I see in the code is default value and not what was selected from what I have build with AJAX.(Even that on the screen I do see the correct values in the select options...)
My backend is Django .
My Django form formatted in following way.
class MassPaymentForm(forms.ModelForm):
leaseterm = forms.ModelChoiceField(queryset=LeaseTerm.objects.none()) # Need to populate this using jquery
lease= forms.ModelChoiceField(queryset=Lease.objects.none()) # Need to populate this using jquery
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
What could be the problem ? And any idea how to solve it?
I have figured out what was the problem
it is in my form file
If I keep the lease and leaseterm fields just in Meta class that it doesn't reset those fields on submit any more . And all my logic finally works as designed.
class MassPaymentForm(forms.ModelForm):
class Meta:
model = LeasePayment
fields = ['lease', 'leaseterm', 'payment_type', 'is_deposit', 'amount', 'method', 'payment_date', 'description']
Can i add dropdownlist to table by using jquery append.
Eg.
$(#table).append("<tr><td>#Html.DropDownList('TP',new SelectList(#Model.RefList, 'Value', 'Text',#Model.Ref))</td></tr>");
I dont known how to change this "#Html.Dropdownlist" to valid string.
you cannot add a server control with javascript, you can add an HTML select and load the options using ajax
$('#table').append('<select id="mySelect"></select>');
Example:
$.ajax({
url: "myServiceURL"
}).done(function(myOptions) {
$.each(myOptions, function(key, value) {
$('#mySelect')
.append($("<option></option>")
.attr("value",key)
.text(value));
});
});
This Code will append Select menu to the last row of the table.
var select_list = '<select id="list">';
//you can add more options by repeating the next line & change text,value
select_list += '<option value="changevalue">change text</option>';
select_list += '</select>';
$("#table").append("<tr><td>"+select_list+"</td></tr>");
How do I set default value on an input box with select2? Here is my HTML:
<input type="text" id="itemId0" value="Item no. 1">
and my javascript:
$("#itemId0").select2({
placeholder: 'Select a product',
formatResult: productFormatResult,
formatSelection: productFormatSelection,
dropdownClass: 'bigdrop',
escapeMarkup: function(m) { return m; },
minimumInputLength:1,
ajax: {
url: '/api/productSearch',
dataType: 'json',
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {results:data};
}
}
});
function productFormatResult(product) {
var html = "<table><tr>";
html += "<td>";
html += product.itemName ;
html += "</td></tr></table>";
return html;
}
function productFormatSelection(product) {
var selected = "<input type='hidden' name='itemId' value='"+product.id+"'/>";
return selected + product.itemName;
}
Here is the issue:
If I won't initialize my input box into a select2 box, I can display the default value of my input box which is "Item no. 1":
but when I initialize it with select2 eg. $("#itemId0").select2({code here}); I can't then display the default value of my text box:
Anyone knows how can I display the default value please?
You need to utilize the initSelection method as described in Select2's documentation.
From the documentation:
Called when Select2 is created to allow the user to initialize the selection based on the value of the element select2 is attached to.
In your case, take a look at the Loading Remote Data example as it shows how to incorporate it along with AJAX requests.
I hope this helps.
Old initial selections with initSelection
In the past, Select2 required an option called initSelection that was
defined whenever a custom data source was being used, allowing for the
initial selection for the component to be determined. This has been
replaced by the current method on the data adapter.
{
initSelection : function (element, callback) {
var data = [];
$(element.val()).each(function () {
data.push({id: this, text: this});
});
callback(data);
}
}
You can use the set value too.
You should directly call .val on the underlying element
instead. If you needed the second parameter (triggerChange), you
should also call .trigger("change") on the element.
$("select").val("1").trigger("change"); // instead of $("select").select2("val", "1");
Refs:
https://select2.github.io/announcements-4.0.html
https://github.com/select2/select2/issues/2086
http://jsfiddle.net/F46NA/7/
If you have an input element, declare it as follows. Remember to populate the value field as well.
<input type="hidden" name="player" id="player" data-init-text="bla bla" value="bla bla" >
Write an initSelection function
initSelection : function (element, callback) {
var elementText = $(element).attr('data-init-text');
callback({"text":elementText,"id":elementText});
}
make sure that this call back has same key value pair as the one return by the ajax call.
callback({"text":elementText,"id":elementText});
I have noticed that keeping the value field empty will keep the input empty by default so remember to populate it as well.
The method initSelection can not have an empty value attribute to work properly.
That was my problem.
Hopefully this will help someone.
You can easily change the value of your select input by just putting the id's of your selected option in data attribute of your select input. And then in javascript
var select = $('.select');
var data = $(select).data('val');
$(select).val(data);
And after that initialize select2 on your select input
$(select).select2();
Here is the fiddle https://jsfiddle.net/zeeshanu/ozxo0wye/
you dont need ajax or json, you just need to put SELETED tag into your OPTION and SELECT2 will display the init value.
This works for me: 'Add default value to the head of array'
data.unshift({'id':-1, 'name':'xxx'});
$('#id_xxx).select2({
placeholder: '--- SELECT ---',
data: data,
allowClear: true,
width: '100%'
});
However, official doc says:
You can set default options by calling $.fn.select2.defaults.set("key", "value").
There is no example though.
I found the extremly simple solution.
You have to pass the ID and the Name of the default option and insert it like HTML inside
var html = ' <option value="defaultID">defaultName</option>';
$(".js-example-basic-single").html(html);
How to get defaultID or defaultName depends on your code.
For instance in ASP .Net MVC you can do it like
<select id="PersonalID" class="js-example-basic-single form-control form-control-sm" name="PersonalID">
<option value="#Model.PersonalID">#ViewBag.PersonalInfo</option>
</select>
I use another approach in this specific configuration:
- multiple="multiple"
- populating from AJAX on user's search
$("#UserID").select2({
placeholder: 'Input user name',
"language": {
"noResults": function () {
return "Sorry, bro!";
}
},
dropdownParent: $("#UserID").parent(),
ajax: {
delay: 200,
url: '#Url.Action("GetUserAsJSON", "AppEmail")',
cache: true,
dataType: 'json',
data: function (params) {
var query = {
search: params.term,
page: params.page || 1
};
// Query parameters will be ?search=[term]&page=[page]
return query;
}
}
});
There are few steps to get working my solution
1) Keep each added value in a global array.
var selectedIDs = new Array();
$("#UserID").on('change', function (e) {
//this returns all the selected item
selectedIDs = $(this).val();
});
2) So when you save data you always have selectedIDs array.
3) When you refresh/load webpage just populate selectedIDs with saved data for later resaving/editing from one hand and from another hand populate select2 object
In my case of ASP MVC it looks like this but you can use JQuery to insert <option> to <select>.
<select id="UserID" class="js-example-basic-multiple form-control border" name="UserID" style="width:100%!important;" multiple="multiple">
foreach (var item in Model.ToUsers)
{
<option selected="selected" id="#item.ID" value="#item.ID">#item.Value</option>
}
</select>