Issue with select default value of select menu in Jquery? - javascript

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);

Related

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 getting selected value of select menu in query?

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);

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);
});
});

Best way to create a dynamic Select (Dropdown) list?

I'm using jQuery and jqGrid.
I'm trying to populate a select list dynamically, one for each row and I need to add a click event to it. When the select list is being populated I grab the index of the item I want selected, and then after all items are add I'm trying to set the selected item.
I've tried
$("#taskList")[0].selectedIndex = taskIndex;
$("#taskList").selectOptions(taskIndex, true);
$("#taskList").val(1); //Tried to see if I could select any index and no luck.
$("#taskList option[value=" + taskIndex + "]").attr("selected", true);
So this means I'm probably populating the list incorrectly...
var taskList = document.createElement("select");
var taskIndex = 0;
for (var i = 0; i < result.TaskTypes.length; i++) {
$(taskList).addOption(result.TaskTypes[i].TaskId, result.TaskTypes[i].TaskName);
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskIndex = i;
}
Is there a better way?
I tried this but I couldn't add the click event to it. The proper item was selected though.
var taskList = "<select name='taskList' Enabled='true'>";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
The way I would have done it, is in your first example - instead of using the jQuery API for addOption, use the DOM API, like this:
var option = document.createElement("option");
option.innerHTML = result.TaskTypes[i].TaskName;
option.value = result.TaskTypes[i].TaskId;
option.onclick = myClickHandler;
taskList.add(option, null);
Then after the loop you can just use:
taskList.selectedIndex = taskIndex;
to have the select list positioned to your required default selection.
I haven't used jQuery extensively, but I think its a good idea not to neglect the DOM API - its often not as convenient as the shortcuts that jQuery and other libraries offer, but these extend DOM capabilities and should not come instead of the DOM.
You can set the selected index like this:
$("#taskList").selectedIndex = taskIndex;
Falling under the "better way" category, JQuery lets you use an each loop instead of creating the for loops manually.
jQuery.each(result.TaskTypes, function(i, val) {
$("#" + i).append(document.createTextNode(" - " + val));
});
Got it- a good solid 8 hours later.
var taskList = "<select name='taskList' Enabled='true' onClick='$(\"#hoursBx\").valid()' >";
for (var i = 0; i < result.TaskTypes.length; i++) {
if (result.TaskTypes[i].TaskName == rowData.TaskType)
taskList += "<option selected> " + result.TaskTypes[i].TaskName + "</option>";
else
taskList += "<option>" + result.TaskTypes[i].TaskName + "</option>";
}
taskList += "</select>";
I'm using jQuery's Validator to verify the value in the $("#hoursBx") (a text box in the current row).
Adding the onClick works.

Categories