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]
Related
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.
This question already has answers here:
Set select option 'selected', by value
(28 answers)
Closed 5 years ago.
I am running through a list of items in an array. Outputting those options to via JQuery to a html SELECT.
I want to compare the current item in the array to a previously selected variable and set the <option> attribute to selected.
But it fails to add the attribute.
What am I doing wrong?
//PHP
$myAnimalArray = some filled array();
$s_current_selected = "Zebra";
//SOME HTML FORM
<select class="form-control" id="animals_select" name="animals_select"></select>
JQuery
<script type="text/javascript">
$(document).ready(function () {
let animal_array = <?php echo json_encode($myAnimalArray); ?>;
let animals_select = document.getElementById("animals_select");
let current_selected = "<?php echo $s_current_selected; ?>";
update_animal_options(animal_array);
function update_animal_options(optionsArray) {
$(animals_select).empty(); //remove any prior entries
for (let i = 0; i < optionsArray.length; i++) {
$(animals_select).append('<option value=' + optionsArray[i] + '>' + optionsArray[i] + '</option>');
// HERE IS WHERE MY PROBLEM IS
if (optionsArray[i] == current_selected) {
$(animals_select).attr('selected', 'selected');
}
}
}
});
</script>
Attribute selected is a part of <option>, not <select> itself. You should modify your code as:
function update_animal_options(optionsArray) {
$(animals_select).empty();
$(animals_select).append(
'<option value=' + optionsArray[i]
+ (optionsArray[i] == current_selected? ' selected' : '') + '>'
+ optionsArray[i] + '</option>'
);
}
ALso, it's always a good idea to wrap attribute values in quotes. Otherwise code like value=Some value here will not be treated as you expect.
I have a constructor and have created some instances of it which I have placed in an array. What I am trying to do is to display the value of said object into the empty list depending on what I choose from a list of options. Here is what I have done so far:
<ul id="contactinfo"></ul>
<select id="dropdown">
<option value="email">Email</option>
<option value="number">Phone Number</option>
</select>
function ContactList (name, email, number) {
this.name = name;
this.email = email;
this.number = number;
}
var christian = new ContactList('Christian', 'christian#yahoo.com', '323-555-124');
var contactarray = [christian];
function displayinfo () {
var dropdown = $('#dropdown').val();
var number = $('#dropdown').val('number');
var email = $('#dropdown').val('email');
for (i = 0; i < contactarray.length; i++) {
if (dropdown == number) {
$('#contactinfo').append('<li>' + contactarray[i].number + '</li>');
} else {
$('#contactinfo').append('<li>' + contactarray[i].email + '</li>');
}
}
}
displayinfo();
Firstly, note that the main issue with your current code is that $('#dropdown').val(), $('#dropdown').val('number') and $('#dropdown').val('email') all return the same thing - the dropdown in a jQuery object. Also note the latter two are also setting the value to that provided, so the JS would always only retrieve the email as that was what is set last.
To fix it, you can take the value selected in the dropdown and retrieve that property from the contactarray element directly. Try this:
function displayinfo () {
var $contacts = $('#contactinfo').empty();
for (i = 0; i < contactarray.length; i++) {
$contacts.append('<li>' + contactarray[i][$('#dropdown').val()] + '</li>');
}
}
Finally, you also need to execute displayinfo when the option in the select is changed, and also clear out any previously appended li. Check out the fiddle below for a full working example:
Working example
How do I split this string:
waterfowl||tvs||guitar||pillow||mouse
...by ||?
Then, I'd like to create a select list like this:
<select name="options" id="options">
<option value="waterfowl">waterfowl</option>
<option value="tvs">tvs</option>
<option value="guitar">guitar</option>
<option value="pillow">pillow</option>
<option value="mouse">mouse</option>
</select>
var options = 'waterfowl||tvs||guitar||pillow||mouse';
$( '#someDiv' ).html( '<select name="options" id="options">'
+ options.replace(/(\w+)\|*/g, '<option value="$1">$1</option>')
+ '</select>' );
// Turns a string in to a combo box based on:
// #d Delimiter to split the string up by
// #so Select box attributes (adding name="foo" means passing {name:'foo'})
// Result: jQuery object of the new select element, populated with the items
// from the string
String.prototype.toSelect = function(d,so){
so = so || {};
var s = $('<select/>',so),
items = this.split(d);
for (var i = 0; i < items.length; i++){
$('<option/>').val(items[i]).text(items[i]).appendTo(s);
}
return s;
}
// an example
// Append the following string to the body of the document
// after it's been converted in to a <Select> element
$('body').append("waterfowl||tvs||guitar||pillow||mouse".toSelect('||',{
name: 'select',
id: 'select'
}));
Version with a bit more flexibility (and jQuery abilities): http://jsfiddle.net/j6DjR/
Preamble:
I used a <select> element with id and name attributes of
"assorted". "options" is a terrible id/name for a form element.
Read here for more: http://www.fortybelow.ca/hosted/comp-lang-javascript/faq/names/
Code:
No mess, no fuss.
(commonElements.testing is the form containing the <select> element)
var commonElements =
{
"testing": document.getElementById("testing"),
"assorted": document.getElementById("assorted")
},
options = "waterfowl||tvs||guitar||pillow||mouse";
function addOptions (optionList)
{
var i = 0,
limit = optionList.length,
parent = commonElements.assorted,
option;
for (i;i<limit;i++)
{
option = document.createElement(
"option"
);
option.text = optionList[i];
option.value = optionList[i];
parent.add(option, null);
}
}
function createOptions (toSplit)
{
var optionList = toSplit.split("||");
addOptions(optionList);
}
createOptions(options);
Working Link (with full code):
http://jsbin.com/ucajep
Try the following:
var input = 'waterfowl||tvs||guitar||pillow||mouse';
var split = input.split('||');
var select = $('<select name="options" id="options"></select>');
$.each(split, function(index, value) {
var option = $('<option></option>');
option.attr('value', value);
option.text(value);
select.append(option);
});
$('#idOfContainer').empty().append(select);
Your problem is simple:
Split string, using || as separator.
Loop over the splitted string.
Create a new option element
Set its value and text to the current item
Add the element to containing select element
Here's a simple implementation of it (without using jQuery). I use Array.prototype.forEach and element.textContent (the former being ES5 and latter being non-IE), but it should bring the point across (and they're not hard to shim).
function makeSelect( options, separator ) {
var select = document.createElement( 'select' ),
optionElem;
options.split( separator || '||' ).forEach(function( item ) {
optionElem = document.createElement( 'option' );
optionElem.value =
optionElem.textContent =
item;
select.appendChild( optionElem );
});
return select;
}
var selectElem = makeSelect( 'waterfowl||tvs||guitar||pillow||mouse' );
You can then manipulate selectElem just like you'd manipulate any other DOM element.
You can split the string into an array, then iterate through the array building an HTML string that you can then append to the DOM:
var str = 'waterfowl||tvs||guitar||pillow||mouse',//the string to be split
arr = str.split('||'),//the split string, each split stored in an index of an array
out = '';//our output buffer variable
//iterate through each array index
for (var index; index < arr.length; i++) {
//add this index to the output buffer
out += '<option value="' + arr[index] + '">' + arr[index] + '</option>';
}
//add the HTML we've built to the DOM, you can also use `.append(<code>)` instead of `.html(<code>)` but if you are using an ID for your select element then you ant to make sure and replace the HTML
$('#container-element').html('<select name="options" id="options">' + out + '</select>');
Here's a jsfiddle to demonstrate: http://jsfiddle.net/jasper/eb5Dj/
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.