Not 100% sure my question's title accurately states my question, I apologize in advance. Please correct me if my terminology is off here.
Basically, I have a select box. When the user makes a selection I want to create a new select box setting its options using the values stored in an object:
jsFiddle showing my attempt
My Code:
HTML :
<SELECT id="mainIssueType" style="color:#888"size=0>
<OPTION style="color:#888" selected> Issue Type </option>
<OPTION style="color:#888" value="Hotel"> Hotel </option>
<OPTION style="color:#888" value="Flights"> Flights </option>
</SELECT>
SCRIPT :
var tree = {
"Hotel": [{val: "Htl1", text: 'Cancel'},
{val: "Htl2", text: 'Modify'},
{val: "Htl3", text: 'Research'},
{val: "Htl4", text: 'Complaint'}],
"Flights": [{val: "Flt1", text: 'Void'},
{val: "Flt1", text: 'Cancel'},
{val: "Flt1", text: 'Change Flight'},
{val: "Flt1", text: 'Schedule Change'},
{val: "Flt1", text: 'Name Change'}, ]
};
$(function() {
$('#mainIssueType').change(function() {
//get current selected option
var selectVal = $('#mainIssueType :selected').val();
//create a new select box and add to body
var sel = $('<select>').appendTo('body');
//give the new element an id matching
//the selected value from the previous element
sel.attr('id', selectVal);
//set the select box's options using the values
//from the "selectVal" object within the "tree" object
$(tree.selectVal).each(function() {
//tree.selectVal seems to be the problem
sel.append($("<option>").attr('value', this.val).text(this.text));
});
});
});
The tree.selectVal in $(tree.selectVal).each seems to be the problem here. I guess this is not the same as saying tree.Hotel directly as I can get it to work using tree.Hotel as shown here
How can I access the object in tree whose name matches my selectVal variable?
Use $(tree[selectVal]) instead of $(tree.selectVal)
$(function(){
$('#mainIssueType').change(function() {
//get current selected option
var selectVal = $('#mainIssueType :selected').val();
//create a new select box and add to body
var sel = $('<select>').appendTo('body');
//give the new element an id matching
//the selected value from the previous element
sel.attr('id',selectVal);
//set the select box's options using the values
//from the "selectVal" object within the "tree" object
$(tree[selectVal]).each(function() {
//_____^_____________________
//tree.selectVal seems to be the problem
sel.append($("<option>").attr('value',this.val).text(this.text));
});
});
});
FIDDLE DEMO
Related
I'm trying to make an ecommerce site. So what I'm trying to do here is that I have two select tag, the value of the second tag should automatically be listed after selecting a particular data on the first select tag. Meaning suppose, the first tag is for 'Department' whereas the second tag is for categories. So if I select 'Electronics' in the first tag only(not all) categories which are inside Electronics(eg. laptop, smartphone, etc) should appear automatically, same case for cloth which should appear only(top wear, bottom wear, etc). And what I did is that I made the department in a select tag whereas I stored the categories in a javascript array. The following is the code for html...
<select class="products" id="department_select" name="department" onchange="categoryChange(this);">
<option value="empty">Select</option>
<option value="Electronics">Electronics</option>
<option value="Men's clothes">Men's clothes</option>
<option vlaue="Women's clothes">Women's clothes</option>
<option vlaue="Home & Kitchen">Home & Kitchen</option>
<option vlaue="Sports & Fitness">Sports & Fitness</option>
</select><br>
Below is the code where I stored the categories in javascript array..
<script>
// array of possible countries in the same order as they appear in the country selection list
var categoryLists = new Array(5)
categoryLists["empty"] = ["Select"];
categoryLists["Electronics"] = ["Select","Camera", "Desktop", "Laptop", "Mobile", "Smart watch"];
categoryLists["Men's clothes"] = ["Select","Foot wear", "Bottom wear", "Top wear", "Summer clothes", "Winter clothes"];
categoryLists["Women's clothes"] = ["Select","Clothing", "Foot wear", "Saree", "Top wear", "Bottom wear"];
categoryLists["Home & Kitchen"] = ["Select","Living Room Furniture", "Bedroom Furniture", "Office & Study", "Kitchen needs"];
categoryLists["Sports & Fitness"] = ["Select","Cricket", "Football", "Gym Accessories"];
/* CountryChange() is called from the onchange event of a select element.
* param selectObj - the select object which fired the on change event.
*/
function categoryChange(selectObj){
// get the index of the selected option
var idx = selectObj.selectedIndex;
// get the value of the selected option
var which = selectObj.options[idx].value;
// use the selected option value to retrieve the list of items from the countryLists array
cList = categoryLists[which];
// get the country select element via its known id
var cSelect = document.getElementById("category_select");
// remove the current options from the country select
var len = cSelect.options.length;
while(cSelect.options.length > 0){
cSelect.remove(0);
}
var newOption;
// create new options
for(var i=0; i<cList.length; i++){
newOption = document.createElement("option");
newOption.value = cList[i];// assumes option string and value are the same
newOption.text = cList[i];
// add the new option
try{
cSelect.add(newOption);
}
catch(e){
cSelect.appendChild(newOption);
}
}
}
So normally when i stored data from php i used the $categories = $_POST['categories'] and all. But the problem here is that I can't seem to find a way to store the javascript array data into the database. Especially since i'm storing one select tag using php and the second select tag using javascript.
So, guys if you could please help me out here. THANK YOU SO MUCHH...
To store an array into a database, you need to convert it to a string first.
//Convert to string
$categories = json_encode($categories);
//You now use $categories in your mysql queries
I have select name slc_pc and i want to append option by jquery code.
I try these script. But it's not working.
$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true).attr("abc",brand,"123",model));
There are some mistakes in your code. First of all, to set multiple attributes, you need to pass them as an object. Second, the property name and value for the data attributes are incorrect. brand & model should be property and abc & 123 should be their values respectively.
new Option will create an option element which does not have attr method on it. You may use jQuery to create a new element.
Here's the correct way
$('select[name="slc_pc"]')
.append($('<option />') // Create new <option> element
.val('Hello') // Set value as "Hello"
.text('Hello') // Set textContent as "Hello"
.prop('selected', true) // Mark it selected
.data({ // Set multiple data-* attributes
brand: 'abc',
model: '123'
})
);
If you add an ID "slc-pc" to your select element, it's like this in it's basic form:
$('#slc_pc').append($("<option></option>").attr({"value": key, "abc": brand, "123": model }).text(value));
try this one
you have add ) after (new Option("Hello", "Hello", true, true) that and remove ) from last
$("select[name='slc_pc']").append(new Option("Hello", "Hello", true, true)).attr("abc", "brand", "123", "model");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select name='slc_pc'>
<option>select</option>
</select>
$(function(){
var brand = 'test';
var model = '123';
var brand1 = 'abc';
var model1 = '456';
$(".slc_pc").append("<option value='hello' data-brand='" +brand+ "' data-model='" +model+ "'>hello</option><option value='hello1' data-brand='" +brand1+ "' data-model='" +model1+ "'>hello1</option>");
})
$(document).on("change",".slc_pc", function(){
var option = $("option:selected", this);
alert("value : "+ $(this).val() + ", brand : "+$(option).data('brand') + ", model : " + $(option).data('model'));
})
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<select class='slc_pc' name='slc_pc'>
<option value=''>--select--</option>
</select>
it can be done by something like this.
I want to have a drop down select box with options coming from an array and I want to have access to the some property of the selected option and the array index.
So, for example I have an array:
selectOptions = [{id: 1, name: 'name1'}, {id: 2, name: 'name2'}, {id: 3, name: 'name3'}];
and when one of the options is chosen I want to have access to the selected option's id and index position in selectOptions.
Right now I have this for selecting the id:
<select name="currentlySelected" ng-model="selectedId" ng-options="cat.id as cat.name for cat in selectOptions" ng-change="change(selectedId)">
</select>
But I also want to send as an input to the change function the index of the selected option in the selectOptions array. I want to be able to do this:
$scope.change = function ($parentId, $arrayId) {
$scope.currentlySelected = $scope.selectOptions[$arrayId];
$scope.selectedId = $parentId;
};
Does someone know how to do this?
Before I give you a solution I want to first suggest that you dont do what you are trying to do. You are basically keeping track of the same thing twice. You want the selected object and the selected id. If you keep track of the selected object you always have the id as well. I would suggest you try to keep track of just the selected object. When you need the id just use object.id
Why dont you select the object and then sync the property:
<select name="currentlySelected" ng-model="selectedItem"
ng-options="cat as cat.name for cat in selectOptions"
ng-change="change()">
</select>
Then in your code
$scope.change = change;
function change() {
$scope.selectedId = $scope.selectedItem && $scope.selectedItem.id
}
You can use the object as the value reference:
<select name="currentlySelected" ng-model="selectedId" ng-options="cat as cat.name for cat in selectOptions"> <!-- You don't need the ng-change, it's not neccecary -->
And in your controller, you need to save a the reference to the object in the array:
$scope.change = function ($arrayId) {
$scope.currentlySelected = $scope.selectOptions[$arrayId];
console.log($scope.selectedId); // THE MODEL HOLES THE OBJECT ITSELF
};
$scope.change(1); // EXAMPLE for changing the value from the code
Check the sample below, this should help you to get things done
ng-options="{catId: cat.id, index: idx} as cat.name for (idx, cat) in selectOptions"
angular.module('app', []).run(function($rootScope){
$rootScope.selectOptions = [{id: 1, name: 'name1'}, {id: 2, name: 'name2'}, {id: 3, name: 'name3'}];
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="app">
<select name="currentlySelected" ng-model="selectedId" ng-options="{catId: cat.id, index: idx} as cat.name for (idx, cat) in selectOptions">
</select>
<p>
selectedId: {{selectedId}}
</p>
</div>
I have a select list that displays a list languages.
<select name="language_code" id="id_language_code">
<option value="ar">Arabic - العربية</option>
<option value="bg">Bulgarian - Български</option>
<option value="zh-CN">Chinese (Simplified) - 中文 (简体)</option>
<option value="en" selected="selected">English (US)</option>
<option value="fr-CA">French (Canada) - français (Canada)</option>
</select>
I am able to get the text value of the selected value using the following code [returns English (US) from the above select list]:
$('#id_language_code option:selected').text()
How can I get the text value if I pass the option value of 'bg' as a variable when the selected value is still English (US)?
This means that the value returned would be "Bulgarian - Български" when the selected value is still "English (US)".
I have searched Google and SO for an answer, but was unable to find one, so I am thinking that this is not as easy as I 1st thought it was!
Here is an example of how you can use CSS selectors to query the value attribute:
function getOptionTextByValue(value) {
return $('#id_language_code option[value=' + value + ']').text();
}
var bgText = getOptionTextByValue('bg');
Here is a working example
http://plnkr.co/edit/SQ48SmoQkSUgDpQ5BNAx?p=preview
You have some data, and you have the view of this data (html/dom), but it's best if you go data -> view, rather than view -> data.
For example, say you have this array:
var languages = [
{short: "ar", text: "Arabic - العربية"},
{short: "bg", text: "Bulgarian - Български"},
{short: "en", value: "English (US)"}
];
Now you can look things up, for example, "what is the text for the abbreviation 'bg'?"
languages.filter(function(x){ return x.short === 'bg' })[0].text;
Or create DOM nodes from it:
function option(x){
var el = document.createElement('option');
el.value = x.short; el.textContent = el.text;
return el;
}
function select(options){
var el = document.createElement('select');
options.forEach(function(x){ el.appendChild(x); });
return el;
}
var element = select(languages.map(option));
element.id = 'id_language_code';
Hmm, if I understand correctly, you want to retrieve the label associated with a given value of one of the options of the <select> element, which will not necessarily be the currently selected option. Using pure JavaScript approach (aka. No jQuery, since there's already a nice one provided by someone else):
function getOptionLabel(selectId, optionValue){
// Get select element and all options
var sel = document.getElementById(selectId);
var selOpts = sel.options;
// Cycle through each option to compare its value to the desired one
for(var i = 0; i < selOpts.length; i++){
if (selOpts[i].value == optionValue){
return selOpts[i].label;
}
}
// Default return value
return "Option not found.";
}
To get the Bulgarian option from a <select> of the given id, you could call it like so:
getSelectLabel("id_language_code", "bg");
Here's a JSFiddle to demonstrate. Hope this helps! Let me know if you have any questions.
I am using knockout.js, and it's not setting the value of an empty option (Four):
<select data-bind="value: item.widgetValue, attr: {id: item.widgetName, name: item.widgetName}, options: item.options, optionsText: ‘label’, optionsValue: ‘value’” id=”fld-“ name=”fld0”>
<option value=”one”>One</option>
<option value=”two”>Two</option>
<option value=”three”>Three</option>
<option value>Four</option>
...
</select>
This is creating a problem: when you're on any option and try to select Four, it selects One; it will only select Four the second time you try to select it.
I have tried changing the knockout data-bind to fix it:
value: $.trim(item.widgetValue)
This allows you to select Four immediately, but incorrectly shows One as being selected after you submit the form with Four selected.
Any ideas as to what could be causing this, or how to fix it?
You shouldn't be manually setting options if you are using the options binding on your select element. If those are being dynamically created by the binding (ie. you are actually using item.options for your source) then check the objects you are binding the select element to -
item.options probably looks like this (missing a value or is somehow not like the other options) -
item.options = [
{ label: 'someLabel1', value: 'someValue1' },
{ label: 'someLabel2', value: 'someValue2' },
{ label: 'someLabel3', 'someValue3' }
];
but should be a more uniform object like this (well defined model) -
function optionModel(label, value) {
var self = this;
self.label = ko.observable(label);
self.value = ko.observable(value);
}
item.options = [
new optionModel('someLabel1', 'someValue1'),
new optionModel('someLabel2', 'someValue2'),
new optionModel('someLabel3', 'someValue3')
];