Issue with getting selected value of select menu in query? - javascript

There is a select menu in my page which loads the values from DB. I am able to view the values in select menu. but while displaying the selected value, I am not able to display it properly. i.e. If the value contains any spaces it is not getting full value( EX: if I selected "Wilson Garden", I am getting only "Wilson". It is displaying "Wilson Garden" in select box, when I try to get that value by on change event I got only "Wilson",Same thing happen for all the values which has space in it.
my html is code is:
<select name="select-choice-1" id="select-choice-1">
<option value="Select Category">Select Category</select>
</select>
And my Jquery code is as follows,
$("#select-choice").on('change', function(event) {
alert( this.value );
console.log("Category is: " +this.value); // Here I am getting the value..
});
// Store the values dynamically in to select menu..
$(document).on("pagebeforeshow","#homePage",function(){
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select distinct Category from Locationlog;", [], function (tx, res) {
for (var i = 0; i < res.rows.length; i++) {
$("#select-choice").append('<option value='+res.rows.item(i).Category+'>'+res.rows.item(i).Category+'</option>');
}
$("#select-choice").listview('refresh');
});
});
});

It because you didn't quote the attribute. You need to wrap those values around double quotes.
var opt = '<option value="';
opt += res.rows.item(i).Category;
opt += '">';
opt += res.rows.item(i).Category;
opt += '</option>';
$("#select-choice").append(opt);

Related

How to update a dropdown list dynamically using JQuery?

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. :)

I'm trying to source values for a select drop down from a table using JavaScript and jQuery, but the select menu doesn't show any values?

This is the html for the drop down:
<div id="selectEvent" style="width:200px;">
<select>
<option value="0">Select Event:</option>
<option value="1">Event Name</option>
</select>
</div>
This is how I am trying to get the values from a table into the drop down list:
var options = [];
function callback(tx, results) {
var htmlCode;
var cmbType = $("#cboAddEventType");
for (var i = 0; i < results.rows.length; i++)
{
var row = results.rows.item(i);
htmlCode += '<option value="' + row.id + '">' + row.name + '</option>';
}
cmbType.append(htmlCode);
cmbType.html(htmlCode).val(1).change();
}
EventType.selectAll(options, callback);
var sqlInsertEventType = ["INSERT INTO eventType (name) VALUES ('Business')",
"INSERT INTO eventType (name) VALUES ('Personal')",
"INSERT INTO eventType (name) VALUES ('Commercial')"];
But nothing appears in the drop down when I run the application. It's empty. What's wrong? Does it matter what order I link the scripts in the html page or something?
You do not have an html element with id cboAddEventType, you should add this as an id for your select element.
<select id="cboAddEventType">
your code needs some more fixes, but I guess you will get them yourself.

Building HTML Selection field and selecting option with JavaScript Array

I have some JavaScript Arrays that are used to generate HTML selection fileds and then to also make the option a user has selected as the selected opton in the generated Selection list.
I have a working example for a basic JavaScript array. I need help with a more complex JS array though.
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i] + "' "
+ (selectedOption == optionArray[i] ? "selected='selected'" : "")
+ ">" + optionArray[i] + "</option>";
}
return optionsHtml;
};
var typesArray = ['Other', 'SugarCRM', 'Magento', 'Design'];
console.log(buildFormSelection(typesArray, 'SugarCRM'));
This generates this HTML output...
<option value='Other'>Other</option>
<option value='SugarCRM' selected='selected'>SugarCRM</option>
<option value='Magento'>Magento</option>
<option value='Design'>Design</option>
Here is a JSFiddle to show it working. http://jsfiddle.net/jasondavis/4twd8oz1/
My issue is I now need to have the same functionality on a more complex array like this one below. It has an ID and a Name Value...
var milestonesArray = [
['1','Milestone 1'],
['2','milestone 2'],
]
Using similar code as my function above, I need to pull in a user's selected value from a database for example if they have saved the value of 2 then it should select selection option of 2 and show the text milestone 2 from a selection that looks like this...
<option value='1'>milestone 1</option>
<option value='2' selected='selected'>milestone 2</option>
I am not sure how to properly build a JavaScript array that can handle a key and value like this and make my function work with the milestone array.
Any help please?
What you need to do just add another array index to your function like so:
function buildFormSelection(optionArray, selectedOption){
var optionsHtml = '';
for(var i = 0; i < optionArray.length; i++){
optionsHtml += "<option value='" + optionArray[i][0] + "' "
+ (selectedOption == optionArray[i][0] ? "selected='selected'" : "")
+ ">" + optionArray[i][1] + "</option>";
}
return optionsHtml;
};
Where optionArray[i][0] is the value and optionArray[i][1] is the text.
JSFiddle
Answers with lots of code is usually frowned on but this is a trivial solution as #imtheman pointed out in his answer. But not everything needs to be so concise.
function makeOptionElement(value, title, selected) {
var option = document.createElement('option');
option.value = value;
if (selected) {
option.setAttribute('selected', 'selected');
}
option.innerHTML = title;
return option;
}
function dataToOptions(data, selectedIndex) {
var selectList = document.createElement('select');
data.forEach(function(item, index) {
var isSelected = (index === selectedIndex);
var option = makeOptionElement(item[0], item[1], isSelected);
selectList.appendChild(option);
});
return selectList;
}
Essentially, each time you call the array with your variables to be printed, you are calling the contents of the array in the position specified between the [ ]. It may be another array. That you can access as you would any other array. So, it would be:external_array[extrenal_array_index][internal_array_index]

Issue with select default value of select menu in Jquery?

I have one select menu in page2 which will fill dynamic values from DB. Every time when I go to page to I want to select the previously selected value. I am able to get the previously selected value but When I try to set the previously selected value as the default value it does not working. Can any one suggest me what mistake I did? My code is as follows,
$(document).on("pageshow","#saveToDBPage",function(event){
var selecedvalue = $('#select-choice-1 :selected').val();
alert(selecedvalue); // This is Previously selected value........
var db = window.sqlitePlugin.openDatabase({name: "MYDB"});
db.transaction(function (tx) {
tx.executeSql("select distinct Category from Locationlog;", [], function (tx, res) {
$("#select-choice-1").empty();
var optionheading = '<option value="Select Category">Select Category</option>';
$("#select-choice-1").append(optionheading);
for (var i = 0; i < res.rows.length; i++)
{
var opt = '<option value="';
opt += res.rows.item(i).Category;
opt += '">';
opt += res.rows.item(i).Category;
opt += '</option>';
$("#select-choice-1").append(opt).selectmenu('refresh');
$("select#select-choice-1").val(selecedvalue); // IT IS NOT WOKING....
}
});
});
});
try this:
$('#select-choice-1 option[value='+selecedvalue+']').attr("selected", "selected");
or
$('#select-choice-1').val(selecedvalue);
Update: When programmatically manipulating elements like select fields in jQuery Mobile, once you've made the relevant selection, you need to refresh the element so that the user interface is updated:
$('#select-choice-1').val(selecedvalue).attr('selected', true).siblings('option').removeAttr('selected');
$('#select-choice-1').selectmenu("refresh", true);

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