Populating a <select> with data from ajax via javascript - javascript

although I found similar questions the solutions mentioned there wont seem to work for me.
What I'm trying to do:
Fetch all the table names of my database with Ajax
Fill the Table Names as options with respective values into a select field
How far I've come:
My fetch_devices php script echoes:
["test1","test2","test3"]
function FetchDevices(){
alert("Fetching");
$.ajax({
url: 'php/sql/fetch_devices.php',
success: function(devices) {
var elements = Object.keys(devices).length;
var select = document.getElementById("devices");
var option = document.createElement("option");
var i = 0;
while(i < elements)
{
option.text= devices[i];
option.value= devices[i];
select.appendChild(option);
i++;
}
},
cache: false
});
}
But in the end I only see the last option "test3".....
Why is that happening?
Thanks in advance!
Best Regards,

You are overriding the same option. Aslo make use of add(). Change it to
while(i < elements)
{
var option = document.createElement("option");
option.text= devices[i];
option.value= devices[i];
select.add(option);
i++;
}

Related

Dynamically populate select options on a parent window from a child popup window with jQuery

I'm attempting to populate the options on a select element on a parent window with data returned from an ajax call that's called from a child (popup) form. The child form is called from the parent with window.open.
The odd thing is removing the select options works; this succeeds:
$('#selElement', opener.document).find('option').remove().end();
But appending as shown below, throws SCRIPT5022: Exception thrown and not caught.
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
I've also tried
$('#selElement', opener.window.document).append($("<option />").val('').text('---Select---'));
here's the code:
// the line below works; it removes all of the options from the drop-down
$('#selElement', opener.document).find('option').remove().end();
// the ajax call below returns the right data
$.ajax({
url: 'actions.cfc?method=getOptions&returnFormat=json',
dataType: 'json',
// the value being sent here just limits the options returned in the results
data: {myType: $('#myType').val()},
async:false,
success: function(response) {
// getting the right data back
console.log(response);
// the line below results in SCRIPT5022: Exception thrown and not caught
$('#selElement', opener.document).append($("<option />").val('').text('---Select---'));
// never get this far unless I comment out the line above; then the error is thrown here
for (var i = 0; i < response.DATA.length; i++) {
$('#selElement', opener.document).append($("<option />").val(response.DATA[i][0]).text(response.DATA[i][1]));
}
},
error: function (response) {
var r = jQuery.parseJSON(response.responseText);
alert("Message: " + r.Message);
}
});
Any ideas?
If you want to create the element in another document, you have to specify it in the creation like in the target as well:
$('#selElement', opener.document).append($("<option />", opener.document).val('').text('---Select---'));
//Specify the document where the element will be created ^
Otherwise the element will be created in the child document and an error will be thrown when the code tried to add it to the parent document.
Also, you can simplify the option creation:
$("<option value=''>---Select---</option>", opener.document)
Use .map to create you option list and append it to select tag.
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
$('#selElement', opener.document).append('<select>' + option.join('') + '</select>')
const response = { DATA: [
['Mary', 'Mary'],
['Peter', 'Peter'],
['John', 'John'],
['Abel', 'Abel'],
['Mike', 'Mike']
]}
const option = response.DATA.map(item => `<option value='${item[0]}'>${item[1]}</option>`);
option.unshift('<option>-----Select-----</option>');
function myFunction() {
const div = document.getElementById('test');
div.innerHTML = ('<select>' + option.join('') + '</select>');
}
<button onclick="myFunction()">Try it</button>
<div id="test"></div>
This a hybrid jquery/javascript solution I use sometimes ...
var mySubtype = document.getElementById("uploadSubtype");
//Create arrays of options to be added
if(filetype == "2D"){
var array = ['','Proofs','Graphic','Other'];
} else if(filetype == "3D"){
var array = ['','Prelims','Presentation','Controls','Final'];
} else if(filetype == "Accounting"){
var array = ['','W-9','Other'];
}
$( "#uploadSubtype" ).append("<span class='subtype_form_label'>Subtype</span>");
//Create and append select list
var selectList = document.createElement("select");
selectList.id = "subtype";
selectList.name = "subtype";
selectList.classList.add("form_field");
mySubtype.appendChild(selectList);
//Create and append the options
for (var i = 0; i < array.length; i++) {
var option = document.createElement("option");
option.setAttribute("value", array[i]);
option.text = array[i];
selectList.appendChild(option);
}

How do I populate a select input based on 2 radio button values, from mysql

So I have a registration form for archery contests and I want users to select 2 things (their age category and their bow type).
Once those 2 are selected, I want the next field (select) to show up and be populated with information from my mysql database.
This field is a selection of shooting levels, differenciated in classes.
In the database, I have 4 tables.
1 for age category (id, name)
1 for bow type (id, name)
1 for shoot level (id, name)
1 table to link all above (id, ac_id, bt_id, sl_id)
So based on radio 1 being clicked and radio 2 being clicked, I want to fire a query on the link table to only get the shooting levels which belong to the 2 radio values..
Can anyone please help me with this?
Try this:
$('#age').click(function(){
var age = $(this).val();
var bow = $('#bow').val();
function getShootingLevel(age, bow);
});
$('#bow').click(function(){
var age = $('#age').val();
var bow = $(this).val();
function getShootingLevel(age, bow);
});
function getShootingLevel(age, bow)
{
// ajax call
}
P.S. You can also check if radio is selected or not.
I got it :)
$(document).ready(function() {
$('input[type=radio][name=leeftijdscategorie]').change(function() {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
$('input[type=radio][name=schiettechniek]').change(function() {
if($('input[type=radio][name=schiettechniek]').is(':checked')) {
if($('input[type=radio][name=leeftijdscategorie]').is(':checked')) {
// Do stuff
GetLevels($('input[name=leeftijdscategorie]:checked', '#inschrijfformulier').val(),$('input[name=schiettechniek]:checked', '#inschrijfformulier').val())
}
}
});
});
function removeOptions(selectbox) {
var i;
for(i = selectbox.options.length - 1 ; i >= 0 ; i--) {
selectbox.remove(i);
}
}
function GetLevels(agetype,bowtype) {
removeOptions(document.getElementById(\"schietklasse\"));
$.ajax({
url: '/info/wscript.php',
data:
{
agetype: agetype,
bowtype: bowtype
},
type: 'post',
dataType: 'json', // returns response data as json//
success: function(output) {
var selectBox = document.getElementById(\"schietklasse\");
var options = output; //JSON.parse(output);
for(var i = 0, l = options.length; i < l; i++){
var option = options[i];
selectBox.options.add( new Option(option.text, option.value, option.selected) );
}
}
});
}
I basically made this radio check seperate (so double) because I want people to be able to change their choice. Now, it fires a POST to a php file which gets the information and returns it as JSON.

How do I set dropdown option selected by looking at MVC URL

Hello and thank you for making stackoverflow such a great resource for learning programmers like me. I've been reading lots of answers on here to help with my first MVC project, this is my first time asking.
Here is my dropdown HTML
<div class="dropdown">
<select id="assetSelect" onchange="location = this.options[this.selectedIndex].value;">
<option value="/History/Index/All">All Assets</option>
#foreach (var item in Model.NodeInfo)
{
<option value="/History/Index/#item.node.name">#item.node.name</option>
}
</select>
</div>
Once an item is selected from the dropdown, the url will look like this
http://web.site/History/Index/G0000106
Now I'm trying to grab that last part of the URL (in this case G0000106) and set the corresponding dropdown option to selected. Here is the javascript I have pieced together so far but it's not working.
$('#assetSelect').find('option').each(function () {
function getCurrentPageId() {
var params = window.location.href.split('/');
var i = params.length;
var pageId = params[i];
return pageId;
}
var currentPageId = getCurrentPageId();
var $this = $(this);
if ($this.text() == currentPageId) {
$this.attr('selected', 'selected');
return false;
}
});
Will this function work with the one that populates the dropdown list? Is this the best way or is there an HTML helper that can do it? Any help is appreciated, thanks!
Option 1. You can simplify your code significantly:
function getCurrentPageId() {
var params = window.location.href.split('/');
return params[params.length - 1];
}
var pageId = getCurrentPageId();
$('#assetSelect').find('option:contains(' + pageId + ')').prop('selected', true);
Anyway, your problem was in this line:
var i = params.length;
var pageId = params[i];
It should be params[i - 1], since you want to get the last array element.
Option 2. An even simpler approach which should also work for you is to use location.pathname:
$('#assetSelect').val(window.location.pathname);

using jquery .html(), i cant pass an id through to a function

sorry if confusing.. but i am this code:
$(document).ready(function(){
$("button.yo1").click(function(){
$("div.class1").html("<h1> </h1><h1><br /><select id='multi2' style='width:193px;'></select><br /></h1><button>Pick Class</button>")
});
});
and 'multi2' can't be found .. do i have to pass a parameter or variable?. here is the function to get multi2
function childless() {
var s = document.getElementById('multi2');
var ar = [1,2,3];
for(var i=0; i<ar.length; i++) {
var option = document.createElement('option');
option.text = ar[i];
option.value = ar[i];
s.options[i] = option;
}
}
it works if i dont change the div, any ideas?
Well, the childless() function can't be called unless button.yo1 has been clicked
$(document).ready(function(){
$("button.yo1").click(function(){
$("div.class1").html("<h1> </h1><h1><br /><select id='multi2' style='width:193px;'></select><br /></h1><button>Pick Class</button>");
childless(); // <---call childless() after the HTML content has been added.
});
});
Although I'd wonder why you want to recreate the content with each click of div.class1.

How to create a dynamic SELECT drop-down list in JavaScript/jQuery?

I want to display the all the department names in the Dept Table in a combo box.
I have a function which fetches all the Dept name.
How can I dynamically create combo box in runtime, using javaScript or jQuery.
HTML CODE
<select id="searchDepartments">
</select> <input type="button" value="Search" onClick="search();" />
JavaScript function
function getDepartments(){
EmployeeManagement.getDeptList(function(deptList/*contains n-(dept.id, dept.name)*/{
for(i = 0; i<deptList.length; i++){
How can I able to write a code that generates(adds) options to the list?
The process is to create an option node for each item in the list, and add it as a child of the select element.
In plain javascript:
var sel = document.getElementById('searchDepartments');
var opt = null;
for(i = 0; i<deptList.length; i++) {
opt = document.createElement('option');
opt.value = deptList[i].id;
opt.innerHTML = deptList[i].name;
sel.appendChild(opt);
}
There's a plugin that already does this, you may want to check it out. Another benefit of this plugin, is that it has autocomplete built in.
A drop-down combo box, or a select box
into which you can type text to narrow
down the visible result set. This code
is a compilation of the JQuery
Autocomplete plugin as well as other
JQuery plugins, and is still in the
alpha stage of development.
A plain and simple JavaScript script would look as follows:
function AddOption(comboBoxID, displayText, displayValue)
{
var optionItem = document.createElement("option");
optionItem.text = displayText;
optionItem.value = displayValue;
document.getElementById(comboBoxID).options.add(optionItem);
}
You can use the following generic function:
function addOption(text,value,cmbId) {
var newOption = new Option(text, value);
var lst = document.getElementById(cmbId);
if (lst) lst.options[lst.options.length] = newOption;
}
You can create a datalist new option in html5:
<input type="text" class="form-control" id="your_id" list="your_list"
placeholder="Status"/>
<datalist id="your_list">
</datalist>
and fill it with a jquery .append function:
for(var i=0, len=resultado.response['id'].length; i<len; i++)
{
list += '<option value="' +resultado.response['data'][i]+" ( "+resultado.response['id'][i]+" ) "+ '"></option>';
}
dataList.html(list);

Categories

Resources