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. :)
Related
I have a set of options that are being tabulated dynamically.
Eg: Below is a sample set of options that are being tabulated:
option1
option2
option3
Here I am not explicitly setting any option as default and hence, by convention it is taking option1 as default.
However, what I want to do in my use case is search through the entire options and check if there is an option named option3 and if it exists, then set it as default by adding the selected=selected attribute.
Below is the code snippet of concern:
1. HTML
<div class="form-grp">
<label for="selectOption">Select Option</label>
<select class="form-ctl" id="selectTemplate" data-field-type="option" class="tempList">
</select>
</div>
2. JS
var optionList = _.map(optObj, function(opt){
return '<option>' + option.name + '</option>';
});
$('[data-field-type="option"]').html(optionList);
Here, optionList is an object and I am fetching the option name from the object.
Can someone please help me with this.
I tried the following but with no luck.
var html = _.map(templates, function (template) {
for(i=0;i<templates.length;i++){
if(template.name=="story"){
$( function() {
$(".tempList option:selected").attr("selected", "selected");
});
}
return '<option>'+ template.name + '</option>';
}
});
Is it possible to do it without using the id selector?. Or is there any other way to simply loop through the options and then add the selected attribute to the option of interest?.
Thanks very much in advance. Any help or suggestion is highly appreciated.
If I understood you correctly you want to set an option as selected by its content, so you can do it inside it like so:
const optObj = [
{name: "Option1"},
{name: "Option2"},
{name: "Option3"},
];
const optionList = optObj.map(function(option){
return '<option>' + option.name + '</option>';
});
$('[data-field-type="option"]').html(optionList);
function selectOptionByContent(content) {
$(`select option:contains("${content}")`).prop('selected',true);
}
selectOptionByContent("Option3");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-grp">
<label for="selectOption">Select Option</label>
<select class="form-ctl" id="selectTemplate" data-field-type="option" class="tempList">
</select>
</div>
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 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>
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
);
});
I have a multiselect dropdown inside a table
<td>
<select multiple="multiple" name="multiple" id="multiple" class="required">
</select>
</td>
The option values are populated with json data.
for(var i=0;i<jsonString.length;i++){
var name=jsonString[i].Name;
$('#multiple').append('<option value=' + name + '>' + name + '</option>');
}
When the user start selection i am trying to display each selected item inside a paragraph
<script>
function displayVals() {
var multipleValues = $("#multiple").val() || [];
$("p").html( " <b>Selected Properties:</b> " +
multipleValues.join(", "));
}
$("select").change(displayVals);
displayVals();
</script>
But in the paragraph i get just one word per selection, not the complete name. (Say If i select "some text" i get only "some"). Can somebody point out where is the error?
While populating with JSON data use
<option values= > instead of `<option value>
Working fine for me now.`