Populate html select options via http request - javascript

I have a drop-down that I've been hardcoding but would like to talk with an api to get values. Example here:
<div class="ui-widget">
<label>Your preferred programming language: </label>
<select id="combobox">
<option value="">Select one...</option>
<option value="ActionScript">ActionScript</option>
<option value="AppleScript">AppleScript</option>
<option value="Asp">Asp</option>
<option value="BASIC">BASIC</option>
<option value="C">C</option>
<option value="C++">C++</option>
<option value="Clojure">Clojure</option>
<option value="COBOL">COBOL</option>
<option value="ColdFusion">ColdFusion</option>
<option value="Erlang">Erlang</option>
<option value="Fortran">Fortran</option>
<option value="Groovy">Groovy</option>
<option value="Haskell">Haskell</option>
<option value="Java">Java</option>
<option value="JavaScript">JavaScript</option>
<option value="Lisp">Lisp</option>
<option value="Perl">Perl</option>
<option value="PHP">PHP</option>
<option value="Python">Python</option>
<option value="Ruby">Ruby</option>
<option value="Scala">Scala</option>
<option value="Scheme">Scheme</option>
</select>
</div>
Is there a way to populate all of the options given the api call will result in a list? I currently have a java controller mapped to a http request which returns a list. Just not familiar with html/js to know how to populate (or if it's possible) to populate the options from this call.

Yes its quite easy, see this I just made:
let elements = ["hey", "you", "are", "beautiful"]
let select = document.querySelector("#myid")
for (let elt of elements){
let option = document.createElement("option");
option.text = elt;
option.value = elt;
select.appendChild(option);
}
<select id="myid">
</select>

function populateSelect(optionArray){
document.getElementById("combobox").innerHTML = "";
var optionList = "";
for(var i=0;i<optionArray.length;i++){
optionList += "<option value='"+optionArray[i]+"'>"+optionArray[i]+"</option>"
}
document.getElementById("combobox").innerHTML = optionList;
}//End function
If you wanted a vanilla javascript way of implementing your solution. optionArray
is an array of string which consists of the names of your data returned by the API.

I'll share what I have:
This is the select html:
<select
id="doctor"
name="doctor"
class="form-control chosen-select"
data-source="/getDoctors"
data-valueKey="id"
data-displayKey="nombres"
data-displayApellidoP="apellidoP"
data-displayApellidoM="apellidoM"
onchange="updateSelects(this.id)">
</select>
So in the js code:
function loadSelects(callback){
var count = $("select[data-source]").length;
$('select[data-source]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-source'),
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val(option[$select.attr('data-valueKey')])
.text(option[$select.attr('data-displayKey')]);
$select.append($option);
});
if (!--count){
callback();
}
});
});
}
You just add it to the document ready:
$(document).ready(function() {
loadSelects();
}
Lastly, make sure you /request (in this case /getDoctors) respond the json format.

Related

Car Make/Model dynamic dropdown

I'm setting up a new form on my site, and I'm using some code I found here (Vehicle drop down selector). However, I'm using this code within a form, and once the form is submitted, the values for make/model aren't changed to their respective names, instead showing their form values. Being a complete JS noob, how would I go about changing the values submitted from values to make/model names?
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
$model.html($options.filter('[value="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
var $model = $('#model'),
$year = $('#year'),
$yearOptions = $year.find('option');
$model.on('change', function() {
$year.html($yearOptions.filter('[value="' + this.value + '"]'));
$year.trigger('change');
}).trigger('change');
var $year = $('#year'),
$identifier = $('#identifier'),
$identifierOptions = $identifier.find('option');
$year.on('change', function() {
var filteredIdetifiers = $identifierOptions.filter('[value="' + this.value + '"]');
debugger
if (!($("#make").val() == 3 && $("#model option:selected").text() == 'Falcon')) {
filteredIdetifiers = filteredIdetifiers.filter(function(i, e) {
return e.value !== '3'
});
}
$identifier.html(filteredIdetifiers);
$identifier.trigger('change');
}).trigger('change');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!-- Vehicle Brand Selector List -->
<select name="make" id="make">
<option value="0">Make</option>
<option value="1">BMW</option>
<option value="2">Daewoo</option>
<option value="3">Ford</option>
<option value="4">Holden</option>
<option value="5">Honda</option>
<option value="6">Hyundai</option>
<option value="7">Isuzu</option>
<option value="8">Kia</option>
<option value="9">Lexus</option>
<option value="10">Mazda</option>
<option value="11">Mitsubishi</option>
<option value="12">Nissan</option>
<option value="13">Peugeot</option>
<option value="14">Subaru</option>
<option value="15">Suzuki</option>
<option value="16">Toyota</option>
<option value="17">Volkswagen</option>
</select>
<!-- Vehicle Model List -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="1">318i</option>
<option class="lanos" value="2">Lanos</option>
<option class="courier" value="3">Courier</option>
<option class="falcon" value="3">Falcon</option>
<option class="festiva" value="3">Festiva</option>
<option class="fiesta" value="3">Fiesta</option>
<option class="focus" value="3">Focus</option>
<option class="laser" value="3">Laser</option>
<option class="ranger" value="3">Ranger</option>
<option class="territory" value="3">Territory</option>
<option class="astra" value="4">Astra</option>
<option class="barina" value="4">Barina</option>
<option class="captiva" value="4">Captiva</option>
<option class="colorado" value="4">Colorado</option>
<option class="commodore" value="4">Commodore</option>
<option class="cruze" value="4">Cruze</option>
<option class="rodeo" value="4">Rodeo</option>
<option class="viva" value="4">Viva</option>
</select>
<!-- Vehicle Year List -->
<select name="year" id="year">
<option value="0">Year</option>
<option value="1">1998</option>
<option value="1">1999</option>
<option value="1">2000</option>
<option value="1">2001</option>
<option value="1">2002</option>
<option value="1">2003</option>
<option value="1">2004</option>
<option value="1">2005</option>
<option value="2">1997</option>
<option value="2">1998</option>
<option value="2">1999</option>
<option value="2">2000</option>
<option value="2">2001</option>
<option value="2">2002</option>
<option value="2">2003</option>
<option value="3">1991-1999</option>
<option value="4">1997-2007</option>
<option value="5">1997-2007</option>
<option value="3">2002</option>
<option value="3">2003</option>
<option value="3">2004</option>
<option value="3">2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
<option value="4">1997-2005</option>
</select>
<!-- Vehicle Identity List -->
<select name="identifier" id="identifier">
<option value="0">Type</option>
<option class="E46" value="1">E46</option>
<option class="1997-2003" value="2">N/A</option>
<option class="1997-2007" value="4">N/A</option>
<option class="1997-2007" value="5">N/A</option>
<option class="5041618" value="3">BA</option>
<option class="1997-2005" value="3">AU</option>
<option class="1997-2005" value="3">AU2</option>
<option class="1997-2005" value="4">N/A</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
<option class="1997-2005" value="4">1997-2005</option>
</select>
In every <option> tag there is an attribute called value. This value attribute is what is returned at as the value of the dropdown when that option is selected. Seems like in the code you found they are all simply set to numbers. You can set them to be whatever you want though:
<option value="Ford">Ford</option>
<option class="focus" value="Focus">Focus</option>
FIXING DYNAMIC OPTIONS
I see that modifying the values directly affect how the dynamic options are displayed. For example the value attribute of the car model dropdown is used to filter the car make dropdown by only displaying options with the same value. Instead of using the model dropdown's value attributes to compare with make, we can add a new data- attribute called data-make and filter the model dropdown based on that instead. This allows you to freely modify the value attribute in model. The example code below shows this. You would need to modify your JS so model affects year, and year affects identifier in the same way.
$(document).ready(function() {
var $make = $('#make'),
$model = $('#model'),
$options = $model.find('option');
$make.on('change', function() {
// We now filter model using the data-make attribute, not value
$model.html($options.filter('[data-make="' + this.value + '"]'));
$model.trigger('change');
}).trigger('change');
$('#carForm').submit(function(e) {
e.preventDefault();
let formData = $(this).serializeArray();
let data = {};
for (let i = 0; i < formData.length; i++) {
data[formData[i].name] = formData[i].value;
}
alert('Make: ' + data.make + '\nModel: ' + data.model);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="carForm">
<select name="make" id="make">
<option value="0">Make</option>
<option value="BMW">BMW</option> <!-- These values are now make names -->
<option value="Daewoo">Daewoo</option>
<option value="Ford">Ford</option>
</select>
<!-- Vehicle Model List -->
<!-- Notice the new "data-make" attributes for each -->
<select name="model" id="model">
<option value="0">Model</option>
<option class="318i" value="318i" data-make="BMW">318i</option>
<option class="lanos" value="Lanos" data-make="Daewoo">Lanos</option>
<option class="courier" value="Courier" data-make="Ford">Courier</option>
<option class="falcon" value="Falcon" data-make="Ford">Falcon</option>
<option class="festiva" value="Festiva" data-make="Ford">Festiva</option>
<option class="fiesta" value="Fiesta" data-make="Ford">Fiesta</option>
<option class="focus" value="Focus" data-make="Ford">Focus</option>
</select>
<button type="submit">Submit</button>
</form>
You can get the selected option text like this.
$('#form').submit(function(e) {
e.preventDefault();
var make = $make.find(':selected').text();
}
But it would be good practice to set the value you expect to return as the option value and use a data attribute or class to handle the filtering logic.

What is the simplest way to remove option of select (multiple) when given an array (Pure Javascript only)?

Ok, I got
<select id="selectUsers" multiple>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="mike">Mike</option>
<option value="cake">Cake</option>
</select>
given var removeArray=['mary','cake'];.
After running a function remove(), it should be
<select id="selectUsers" multiple>
<option value="tom">Tom</option>
<option value="mike">Mike</option>
</select>
What is the simplest way to remove option of select (multiple) when given an array (Pure Javascript only)?
Iterate over the elements in the array and use an attribute selector in order to select option element's with that specific value attribute:
var removeArray = ['mary', 'cake'];
var selectElement = document.getElementById('selectUsers');
removeArray.forEach(function(value) {
var option = selectElement.querySelector('option[value="' + value + '"]');
if (option) {
selectElement.removeChild(option);
}
});
<select id="selectUsers" multiple>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="mike">Mike</option>
<option value="cake">Cake</option>
</select>
If there are multiple elements with the same value attribute, you would need to use .querySelectorAll() instead of .querySelector() and iterate over those option elements:
var removeArray = ['mary', 'cake'];
var selectElement = document.getElementById('selectUsers');
removeArray.forEach(function(value) {
var options = selectElement.querySelectorAll('option[value="' + value + '"]');
Array.prototype.forEach.call(options, function (option) {
selectElement.removeChild(option);
});
});
<select id="selectUsers" multiple>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="mike">Mike</option>
<option value="cake">Cake</option>
<option value="cake">Cake</option>
</select>
Of course, you could also take the opposite approach and iterate over all the children option elements and remove them based on the value property:
var removeArray = ['mary', 'cake'];
var selectElement = document.getElementById('selectUsers');
var options = selectElement.querySelectorAll('option');
Array.prototype.forEach.call(options, function(option) {
if (removeArray.indexOf(option.value) > -1) {
selectElement.removeChild(option);
}
});
<select id="selectUsers" multiple>
<option value="tom">Tom</option>
<option value="mary">Mary</option>
<option value="mike">Mike</option>
<option value="cake">Cake</option>
<option value="cake">Cake</option>
</select>

JavaScript dependent

I have two drop downs dependent on each other.
When I'm selecting the FRUIT, I want to show only one Apple value from select2 and hide all the others but when I'm selecting Animal I want to show all the values
Please help me write the Javascript function.
Thanks.
<select name="select1" id="select1">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="select2" id="select2">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>
//This is my java script function
function display(){
var access=document.getElementById("select1");
var list = document.getElementById("select2");
var selectlist=access[access.selectedIndex].value;
if(selectlist="APPLE"){
list.style.visiblity="hidden";
}else{
list.style.visiblity="block";
}
FIDDLE
//Add eventlistener for change-event
document.getElementById("selCategory").addEventListener("change", filter, false);
//Filter function which will filter on selected value from first select.
function filter()
{
var cat = document.getElementById("selCategory");
var opt = document.getElementById("selOptions");
var selectedValue = cat.options[cat.selectedIndex].value;
var firstEl = false;
var firstIndex = 0;
for(var i = 0; i < opt.options.length; i++)
{
if(opt.options[i].value !== selectedValue)
{
opt.options[i].style.display = "none";
}
else
{
opt.options[i].style.display = "block";
if(!firstEl)
{
firstIndex = i;
firstEl = true;
}
}
}
opt.value = opt.options[firstIndex].value;
}
//Execute on first load, second select is filtered from the start.
filter();
<select name="category" id="selCategory">
<option value="1">Fruit</option>
<option value="2">Animal</option>
<option value="3">Bird</option>
<option value="4">Car</option>
</select>
<select name="options" id="selOptions">
<option value="1">Banana</option>
<option value="1">Apple</option>
<option value="1">Orange</option>
<option value="2">Wolf</option>
<option value="2">Fox</option>
<option value="2">Bear</option>
<option value="3">Eagle</option>
<option value="3">Hawk</option>
<option value="4">BWM<option>
</select>

HTML Forms with drop down items, how to remove it from in realtime for the next form?

I have a JSP page that is populating 3 different drop down menus.
They are all populated the same. I am looking for a javascript way that in realtime if they choose one from the dropdown the next one they go to the dropdown list won't have that option in it.
Say you have 3 selects "Select1","Select2",and "Select3". Add onchange event to "Select1":
<script language="javascript">
function Select1_OnChange() {
var elemSelect1 = document.getElementById("Select1");
var elemSelect2 = document.getElementById("Select2");
var elemSelect3 = document.getElementById("Select3");
var selValue = elemSelect1.options[elemSelect1.selectedIndex].value;
elemSelect2.remove(getIndexFromValue(elemSelect2,selValue));
elemSelect3.remove(getIndexFromValue(elemSelect3, selValue));
}
function Select2_OnChange() {
var elemSelect2 = document.getElementById("Select2");
var elemSelect3 = document.getElementById("Select3");
var selValue = elemSelect2.options[elemSelect2.selectedIndex].value;
elemSelect3.remove(getIndexFromValue(elemSelect3, selValue));
}
function getIndexFromValue(objSelect,strValue) {
var ret;
for (i = 0; i < objSelect.options.length; i++) {
if (objSelect.options[i].value == strValue) {
ret = i;
}
}
return ret;
}
</script>
Tags might look like:
<select id="Select1" name="Select1" size="1" onchange="Select1_OnChange()>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<select id="Select2" name="Select2" size="1" onchange="Select2_OnChange()>
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>
<select id="Select3" name="Select3" size="1">
<option value="red">Red</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="yellow">Yellow</option>
</select>

getting the value of dropdown menu's and displaying choice using JS

Once the user chooses which flavour they want, I want to be able to display a message on the webpage with the choices they have made from the drop-downs after the submit button is clicked. Here is what I have so far:
<select name="flavour1" required>
<option value="">Please select a Flavour!</option>
<option value="apple">Apple</option>
<option value="strawberry">Strawberry</option>
<option value="lemon">lemon</option>
<option value="pear">Pear</option>
<option value="cola">Cola</option>
<option value="lime">Lime</option>
</select>
<select name="flavour2" required>
<option value="">Please select a Flavour!</option>
<option value="noflavour">No More Flavours!</option>
<option value="apple">Apple</option>
<option value="strawberry">Strawberry</option>
<option value="lemon">lemon</option>
<option value="pear">Pear</option>
<option value="cola">Cola</option>
<option value="lime">Lime</option>
</select>
<input type="submit" value="Get your Flavour!!" onclick="getFlavour()">
JavaScript to attempt to display message into element with id: "postFlavour"
function getFlavour(){
var flavour1 = getElementById("flavour1").value;
var flavour2 = getElementById("flavour1").value;
document.getElementById("postFlavour").innerHTML = "Congratulations, here are your chosen flavours: "+flavour1+", "+flavour2;
}
function getFlavour(){
var sel1 = getElementById("flavour1");
var sel2 = getElementById("flavour2");
var flavour1 = sel1.options[sel1.selectedIndex];
var flavour2 = sel2.options[sel2.selectedIndex];
document.getElementById("postFlavour").innerHTML = "Congratulation, here are your chosen flavours: "+flavour1+", "+flavour2;
return false;
}

Categories