Dropdown menu list from sqlite database table - javascript

Am trying to get data from an sqlite database table to feed to my dropdown menu list. See my thinking below. The problem is I don’t know how to marry the JS function with the HTML part.
HTML.html
<label for="name"><b>Activity Name:/b></label>
<select name="activity" id="activity" required>
<option value="">--Select--</option>
getActivity()
</select>
JS.js
function getActivity(tx) {
tx.executeSql('SELECT * FROM tblactivity', [], queryActivity, errorHandler);
function queryActivity(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var SelectActivity +='<option value="' + results.rows.item(i).activityID +'">'+ results.rows.item(i).ActivityName +'</Option>';
}
//SelectActivity +="</Option";
document.getElementById("activity").innerHTML =SelectActivity;
}}
Alternatively on HTML.html, incorporating the Function like
<label for="name"><b>Activity Name:/b></label>
<select name="activity" id="activity" required>
<script>
function getActivity(tx) {
tx.executeSql('SELECT * FROM tblactivity', [], queryActivity, errorHandler);
function queryActivity(tx, results) {
var len = results.rows.length;
for (var i = 0; i < len; i++) {
var SelectActivity +='<option value="' + results.rows.item(i).activityID +'">'+ results.rows.item(i).ActivityName +'</Option>';
}
//SelectActivity +="</Option";
document.getElementById("activity").innerHTML =SelectActivity;
}}
</script>
</select>

If you want to populate the options on load I would recommend wrapping your js in
$(document).ready(function() {
//your function
});
This way it will run after the HTML has been loaded, and you don't need to do anything in the HTML side (meaning you should remove you call to your function).
EDIT: That solution is JQuery, if you want a pure JS approach use:
window.onload = function() {
//your function
};
Keep in mind this one will load everything before running, like images and other media; on slower connections users may see an empty select before they get loaded.
EDIT (after comments):
Please check this fiddle: https://jsfiddle.net/chn1oL8m/5/
I think I understood your problem now, and this will help you out, just need to use the query instead of random values (I don't have access to the DB obviously =] )

Related

jquery how to fill select option in my form

enter image description here
The json (data) looks like this
guys! I have a little form. Like this:
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
<input type="submit" value="GO GO GO"/>
</form>
<script src="/add-information/aa.js"></script>
In this little code i receive a json with data from my database:
var data = JSON.parse(response);
console.log(data);
in data there is id and name of the rubric. How can i load all this array in my option list?
I was told to do something like this:
var select = document.getelementById('activity_2'); // id of the select
select.options[i] = new Option(data.id, data.od); // add data?
help me please, how i can fill select with data from 'data'?
THE SOLUTION BY ADEON IS:
var data = JSON.parse(response);
console.log(data);
var select = document.getElementById('activity_2');
for (var i = 0; i < data.data.length; i++) {
select.options[select.length] = new Option(data.data[i].name_rus, data.data[i].id);
}
You need to do these:
1) Your call getelementById should be changed to getElementById otherwise you would receive error.
2) You need to create options string first and then append that string to DOM rather than touching DOM every time you add options. Touching DOM as less as possible is a good idea from performance point of view.
3) To simplify the syntax you can use string interpolation syntax like below:
var select = document.getElementById('activity_2');
//$(select).html('');
var data = [{id:1, name_rom:'a', name_rus:'abc'},{id:2, name_rom:'x', name_rus:'xyz'}];
var options = "";
for (var i = 0; i < data.length; i++) {
options += `<option value=${data[i].id}>${data[i].name_rus}</option>`;//<--string
//interpolation
}
$(select).append(options);
//OR below, so you don't need to call document.getElementById
//$('#activity_2').append(options);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" action="" id="ajaxform">
<input type="text" size="32" maxlength="36" name="name" placeholder="Вaшe имя" val="">
<select id="activity_2" name="activity_2">
<option value="">Exmaple</option>
</select>
You can loop your data and append option html to your select.
var select = document.getelementById('activity_2');
$(select).html('');
for (var i in data) {
$(select).append('<option value=' + data[i] + '>' + data[i] + '</option>');
}
Assuming data is an array, you could iterate over it and apply it to the DOM like so.
var optionString = '';
var data = ['John', 'Josh'];
data.forEach(function(dataItem, index){
optionString += '<option value="' + index + '">' + dataItem + '</option>';
});
$('#activity_2').append(optionString);
Here is a working jsfiddle:
https://jsfiddle.net/9ke5fzqo/
You should use add method which accepts as parameter a new Option.
The constructor of Option looks like this: new Option(text,value).
var array=[{
"text":"text1",
"value":"value1"
},{
"text":"text2",
"value":"value2"
}];
var select = document.getElementById('activity_2');
array.forEach(function(item){
select.add(new Option(item.text,item.value));
});
<select id="activity_2" name="activity_2">
You can use $.append in jquery to add new option into a select input.
Html:
<select id="selinput" name="activity_2"> <option value="">Exmaple</option> </select>
Jquery:
$("#selinput").append('<option value="1">value</option>');
Or you can use jquery.selec2 plugin.

Select list - removing appended elements after using getJSON

In my form I have two items selectors. Selecting the first one should always clear the second list (all elements) and populate it with appended options that I get using getJSON. I have tried at least dozen different ways to do it (e.g. .empty(), .find and .remove) but nothing really works. Thanks in advance!
<form id="devuser" action="#" class="form-horizontal form-seperated" method="post">
<div class="form-body">
<div class="col-md-3"><select id="select1" class="form-control select">
<option value="m">M</option>
<option value="f">F</option>
</select></div>
<div class="col-md-3"><select id="select2" class="form-control select">
</select></div>
</div>
</form>
And here goes js code with .empty() example but I also tried .find('option') and .remove().
$("#select1").change(function() {
var userurl = urldv + $(this).val();
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
$("#select2").append('<option id="al'+i+'" value="'+data[i].im+'"</option>');
$("#device"+i).append(data[i].dn;
}
});
$("#select1").change(function() {
$("#select2").empty();
});
});
Using .empty() should work to remove all the option elements.
Issues:
(1) You are missing a closing parenthesis on the following line:
$("#device"+i).append(data[i].dn;
(2) You are registering a second change-event handler inside the first when you should be just executing the code that is in that handler:
$("#select1").change(function() {
var $select1 = $(this),
$select2 = $("#select2"),
userurl = urldv + $select1.val();
$select1.attr('disabled', true);
$select2.empty();
$.getJSON(userurl).done(function(data) {
var optionHtml= '';
for (var i = 0, len = data.length; i < len; i++) {
optionHtml += '<option id="al' + i + '" value="' + data[i].im + '"</option>';
$("#device" + i).append(data[i].dn);
}
$select2.append(optionHtml);
}).always(function() {
$select1.attr('disabled', false);
});
});
Note:
The code above shows how you can prevent overlapping ajax calls by temporarily disabling the first select element.
As others have pointed out, it is more efficient to append all the option elements at once.
You can try this out. The idea is to load the JSON values to a variable then .html it into the selectbox.
$(function(){
var JSONvalue = '';
$.getJSON(userurl).done(function(data){
for (var i=0, len=data.length; i < len; i++) {
var JSONvalue += ('<option id="al'+i+'" value="'+data[i].im+'"</option>');
}
});
$("#select1").change(function() {
$('#select2').html(JSONvalue);
});
});

Use values from different dropdown menus

I am new to coding, therefore I don't fully understand this piece of code.
What I am trying to achieve is that I want to put in multiple drop down menus.The problem with my code is that it accepts values from only certain drop down menus.
My code helps users select the region, country and state according to what they select in the previous drop down menus. I am using this code because it is similar to what I am planning to achieve.
The issue that I face is that I have about 8 drop down menus whose data need to be used. There are 8 region drop downs, 8 country drop downs, and 8 state drop downs. All in the same page. The code stops working if I put 8 ones. What am I doing wrong?
Can somebody please help me? This is the code:
<form>
Region» <select onchange="set_country(this,country,city_state)" size="1" name="region">
<option value="" selected="selected">SELECT NOTE</option>
<option value=""></option>
<script type="text/javascript">
setRegions(this);
</script>
</select>
Country» <select name="country" size="1" disabled="disabled" onchange="set_city_state(this,city_state)"></select>
City/State» <select name="city_state" size="1" disabled="disabled" onchange="print_city_state(country,this)"></select>
<script>
////////////////////////////////////////////////////////////////////////////
// city_state.js ///////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
var countries = Object();
countries['C'] = '|C|Cm|';
countries['D'] = '|D|Dm|';
////////////////////////////////////////////////////////////////////////////
var city_states = Object();
//C
city_states['C'] = '|032010|335553|';
city_states['Cm'] = '|335543|';
city_states['D'] = '|000232|557775';
city_states['Dm'] = '|000231|557765';
////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
function setRegions()
{
for (region in countries)
document.write('<option value="' + region + '">' + region + '</option>');
}
function set_country(oRegionSel, oCountrySel, oCity_StateSel)
{
var countryArr;
oCountrySel.length = 0;
oCity_StateSel.length = 0;
var region = oRegionSel.options[oRegionSel.selectedIndex].text;
if (countries[region])
{
oCountrySel.disabled = false;
oCity_StateSel.disabled = true;
oCountrySel.options[0] = new Option('SELECT TYPE','');
countryArr = countries[region].split('|');
for (var i = 0; i < countryArr.length; i++)
oCountrySel.options[i + 1] = new Option(countryArr[i], countryArr[i]);
document.getElementById('txtregion').innerHTML = region;
document.getElementById('txtplacename').innerHTML = '';
}
else oCountrySel.disabled = true;
}
function set_city_state(oCountrySel, oCity_StateSel)
{
var city_stateArr;
oCity_StateSel.length = 0;
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
if (city_states[country])
{
oCity_StateSel.disabled = false;
oCity_StateSel.options[0] = new Option('SELECT TAB','');
city_stateArr = city_states[country].split('|');
for (var i = 0; i < city_stateArr.length; i++)
oCity_StateSel.options[i+1] = new Option(city_stateArr[i],city_stateArr[i]);
document.getElementById('txtplacename').innerHTML = country;
}
else oCity_StateSel.disabled = true;
}
function print_city_state(oCountrySel, oCity_StateSel)
{
var country = oCountrySel.options[oCountrySel.selectedIndex].text;
var city_state = oCity_StateSel.options[oCity_StateSel.selectedIndex].text;
if (city_state && city_states[country].indexOf(city_state) != -1)
document.getElementById('txtplacename').innerHTML = city_state + ', ' + country;
else document.getElementById('txtplacename').innerHTML = country;
}
</script>
Please check out the updated code at http://jsfiddle.net/HzJ9J/1/
I have not pasted one javascript code in the Javascript section, because I think that specific code needs to run in the correct place. Not sure if I have to move it to the javascript section.
The call to setRegions(this); is failing because 'setRegions is not yet defined; the function definition hasn't been loaded by the browser yet.
I added an ID attribute to your SELECT:
<select onchange="set_country(this,country,city_state)" size="1" name="region" id="region">
and then moved the call to setRegions to the very last thing before the closing SCRIPT tag. Can't use THIS any more, so I added a document.getElementById:
setRegions(document.getElementById("region"));
Using document.write is in general a bad idea, and will not work when the call to setRegions is moved out of line, as it must be. One can accomplish the same thing using innerHTML, so I changed setRegions to be this:
function setRegions(elem) {
for (region in countries)
elem.innerHTML +='<option value="'+region+'">'+region+'</option>';
}
I also deleted the empty OPTION element from the SELECT. Those changes make your code work, although there may be more things that need adjustment.
I'm supposed to answer questions, not give advice, but if you're not using Firefox and the Firebug debugger, or the similar tool in Chrome, you're working far too hard!
Edited 2014-07-21 to add: Your code:
<script type="text/javascript">
setRegions(document.getElementById("region1"));
</script>
is between the beginning and ending tags for the SELECT with the ID of "region1", and I would have bet that the DOM element would not exist at the time of the call. However, if I move your JavaScript into the head of the document, the region selects work, at least in Firefox. I'm not sure why, and I strongly urge you to move that stuff to the end as I've done in my example, or hook it to onload. The DOM really does have to be set up before you start manipulating it.
However, when I run your code with the changes I just suggested, using the Firebug debugger, it tells me: TypeError: oCountrySel.options is undefined.
Get a copy of Firebug, install it in Firefox, or use the developer tools in Chrome, run your code from your own server environment, and look at the console tab. It really will help you, and it really isn't hard.

How do I get javascript to see updated select value?

I have a page with about 100 dropdown menus that I need to pass to another. So, I've put everything in an array that I'm sending via javascript. However, I'm not sure how to get the javascript to see the changed values of the dropdowns before sending. I mocked up some code to give you an idea of the problem. It only sends the value of the dropdown box at the time the page is initialized. Any help would be appreciated.
<select id="mydropdown">
<option value="Milk">Fresh Milk</option>
<option value="Cheese">Old Cheese</option>
<option value="Bread">Hot Bread</option>
</select>
<script>
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
</script>
<form name="data" method="POST" action="passdata1b.php">
<input type="hidden" name="data">
</form>
<script>
function sendData()
{
// Initialize packed or we get the word 'undefined'
var packed = "";
for (i = 0; (i < data.length); i++) {
if (i > 0) {
packed += ",";
}
packed += escape(data[i]);
}
document.data.data.value = packed;
document.data.submit();
}
</script>
<h1>This is what the array contains:</h1>
<ul>
<script>
for (i = 0; (i < data.length); i++) {
document.write("<li>" + data[i] + "</li>\n");
}
</script>
</ul>
Go to passdata1b.php
Sam's answer was good, except..
data[0] = document.getElementById("mydropdown").value;
..that won't work since it's a dropdown menu. Instead get the value of the selected option. Use this instead:
var zeData = document.getElementById("mydropdown");
data[0] = zeData.options[zeData.selectedIndex].value;
Why can't you put this logic:
var data = new Array();
data[0] = document.getElementById("mydropdown").value;
In your sendData() function?
Comment if you need an example, but this should be a pretty easy fix. That way, when you click the link and run sendData(), it will parse the mydropdown value..instead of doing it on page load.

How can I maintain a a dropdown's current information without repopulating the list?

Currently, I have a drop down list that is populated with team names from a SQL database:
$(".show_hide2").click(function () {
("#team").find("tr:gt(0)").remove();
$(".slidingDiv2").slideToggle();
teams = $.parseJSON(getTeams());
for (i = 0; i < teams.length; i++) {
var team = getTeam(teams[i]);
updateTeamBoard(team);
populateTeamSelection(team);
}
}
Here's the code for populating the dropdown.
JS:
function populateTeamSelection(team) {
var team = $.parseJSON(team);
$("#teamSelection").find("#tr:gt(0)").remove();
$("<option value='" + team.teamID + "'>" + team.teamName + "</option>").appendTo("#teamSelection");
}
HTML:
<div class="slidingDiv2">
<select id="teamSelection">
<option id="default" value="0">Select A Team</option>
</select>
<input type="button" id="teamViewer" value="Team Viewer"></input>
</div>
The problem is, every time I click the show/hide button, it retains the current information in the list and then adds the same information to the list. I'm using AJAX to dynamically generate tables and lists, but for some reason I just can't figure this out and I have a feeling it's rather simple. Any help is greatly appreciated.
Every time you click, populateTeamSelection() gets called. Every time populateTeamSelection() gets called, it appends something to the list. A quick fix is to delete all the items from the list before adding any of them.
You can use $('select').children().remove() to delete all the option items before your for loop.
$(function ($)
{
$populateTeamSelection = function(team)
{
$result = $.parseJSON(team,function(call){$handle = call;});
$result.success(function(){ $data = $handle; });
$result.error(function()
{
//Do something or nothing on error
});
$result.complete(function()
{
//Clear all current options first
$('#teamSelection').html('');
//Populate with new data
$.each($data,function(lable,value)
{
$("#teamSelection").append($("<option></option>").attr("value",value['teamID']).text(value['teamName']));
});
});
};
}(jQuery));
$(document).ready(function()
{
$('.show_hide2').click(function()
{
$(".slidingDiv2").slideToggle();
$populateTeamSelection(team);
});
});

Categories