Append option in select and add data attribute to option - javascript

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.

Related

Setting selected attribute to an option list that is tabulated dynamically

I have a set of options that are being tabulated dynamically.
Eg: Below is a sample set of options that are being tabulated:
option1
option2
option3
Here I am not explicitly setting any option as default and hence, by convention it is taking option1 as default.
However, what I want to do in my use case is search through the entire options and check if there is an option named option3 and if it exists, then set it as default by adding the selected=selected attribute.
Below is the code snippet of concern:
1. HTML
<div class="form-grp">
<label for="selectOption">Select Option</label>
<select class="form-ctl" id="selectTemplate" data-field-type="option" class="tempList">
</select>
</div>
2. JS
var optionList = _.map(optObj, function(opt){
return '<option>' + option.name + '</option>';
});
$('[data-field-type="option"]').html(optionList);
Here, optionList is an object and I am fetching the option name from the object.
Can someone please help me with this.
I tried the following but with no luck.
var html = _.map(templates, function (template) {
for(i=0;i<templates.length;i++){
if(template.name=="story"){
$( function() {
$(".tempList option:selected").attr("selected", "selected");
});
}
return '<option>'+ template.name + '</option>';
}
});
Is it possible to do it without using the id selector?. Or is there any other way to simply loop through the options and then add the selected attribute to the option of interest?.
Thanks very much in advance. Any help or suggestion is highly appreciated.
If I understood you correctly you want to set an option as selected by its content, so you can do it inside it like so:
const optObj = [
{name: "Option1"},
{name: "Option2"},
{name: "Option3"},
];
const optionList = optObj.map(function(option){
return '<option>' + option.name + '</option>';
});
$('[data-field-type="option"]').html(optionList);
function selectOptionByContent(content) {
$(`select option:contains("${content}")`).prop('selected',true);
}
selectOptionByContent("Option3");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-grp">
<label for="selectOption">Select Option</label>
<select class="form-ctl" id="selectTemplate" data-field-type="option" class="tempList">
</select>
</div>

JavaScript dropdown list with objects

I would like to create a dropdown list with JavaScript that contains actual objects instead of just a single value.
For example, I have an object with two members, ID and Name. On the dropdown list, I would like the name to be displayed for each object. However, if someone selects a name, I would like to easily be able to get the associated ID.
Not sure of how to do this without two separate containers, one for what's in the DDL and one that has corresponding indices for IDs.
If i understand you correctly, select already supports this. Option text and option value are two separate things
<select>
<option value="1">Volvo</option>
<option value="2">Saab</option>
<option value="3">Opel</option>
<option value="4">Audi</option>
</select>
Check this fiddle
https://jsfiddle.net/pg92tqka/
When you get the value of the selected option you can get stored id and by this value access the actual object (id can be index in array, ...)
html
<select id="selector"></select>
JS
var data = [
{ name :'david', id:1 },
{ name :'daniel', id:2 }
]
data.forEach(function(item){
var option = document.createElement('option');
option.value = item.id;
option.innerHTML = item.name;
selector.appendChild(option)
})'
selector.onchange = function(){
alert(this.value);
}
see the following fiddle : https://jsfiddle.net/1jcrxoy9/
There's a few ways of doing this, however this is my favorite currently:
JavaScript
var data = [{
id : 1,
name : 'Foo'
}, {
id : 2,
name : 'Bar'
}, {
id : 3,
name : 'Baz'
}];
var select = document.createElement('select');
select.innerHTML = data.map(function(v){
return '<option value="' + v.id + '">' + v.name + '</option>';
}).join('');
Then you can append the select somewhere in your body with all the options.
Use the value attribute for your ID.
var ddl_items = [{ ID: 1, Text: "One" }, { ID: 2, Text: "Two" }];
for (var i = 0; i < ddl_items.length; i++ ) {
$("#ddl").append("<option value='" + ddl_items[i].ID + "'>" + ddl_items[i].Text + "</option>");
}
<select id="ddl">
</select>
Fiddle: https://jsfiddle.net/dap3x83v/

ng option initial value select

I have a dynamic combo box. I want to initialise the value of all combo boxes like this the image below is from adding static values like this
$scope.newObject ={ 0 : "N/P" ,1 : "N/P",2 : "N/P",3 : "N/P"}
so I tried to make for on each item on the list in this code below:
$scope.inifonction = ["N/P","N/A","OK","KO"];
//this is the option inside the combobox
$scope.displaydata = function(index) {
$scope.id = index;
$http.get("/fonctions?id=" + $scope.id).success(function(data) {
$scope.list = data;
for(i=0;i<$scope.list.length;i++)
{
$scope.tab = $scope.list[i].idfonction
//this to get the id of the list in a tab
console.log($scope.tab)
//[1,6,5,3] exemple of data in the console
$scope.newObject ={ tab : "N/P"}
}
});
but I didn't work and it looked like this:
and here's my HTML
<select ng-model="newObject[l.idfonction]" ng-options=" fct for fct in inifonction " class="form-control">
when I insert the data am getting this as a result of that ng-model
Object {1: "N/A", 2: "OK", 3: "N/A", 4: "N/P", tab: "N/P"}
Add this line to every dropdown option in the view:
<option value = "">N/P</option>
UPDATE:
I can see that you have an array specific for the initial values. You could use that to set the value as:
<option value = "">{{inifonction[0]}}</option> //This prints N/P
More, you could set to a scope and use it as :
$scope.tab = "N/P";
<option value = "">{{tab}}</option>
this fixed my issue i hope it helps you all
<select ng-init="newObject[l.idfonction] = inifonction[0] " ng-model="newObject[l.idfonction]" ng-options=" fct for fct in inifonction " class="form-control">

How to pass value in select method in AngularJS

I have one problem in AngularJS. How to pass list value in html select method
Here is my code,
app.js
$scope.subcategory = function() {
var query = "SELECT unit FROM Length;";
$cordovaSQLite.execute(db, query).then(function(res) {
if (res.rows.length > 0) {
var message = "SELECTED -> " + res.rows.item(1).unit;
$scope.list = message;
}
});
}
index.html
<select ng-change="subcategory()" ng-options="x.list for x in subcategory"></select>
You can use function param's to make this work or $scope. For example, parsing subcategory.id (I don't know if id attributes does exists for you) to subselect categories by categoryId. You should also define a model by using ng-model.
View
<select ng-options="x.list for x in subcategory"
ng-model="selectedItem"
ng-change="subcategory()">
</select>
Controller
$scope.subcategory = function() {
//you can also access categoryId with
var query = "SELECT unit FROM Length WHERE id = "+ $scope.selectedItem.id+";";
$cordovaSQLite.execute(db, query).then(function(res) {
if(res.rows.length > 0) {
var message = "SELECTED -> " + res.rows.item(1).unit ;
$scope.list=message;
}
});
}
<select ng-options="x.list for x in subcategory" ng-model="selectedItem" ng-change="subcategory()"></select>
You can have access to the selected option fron inside the subcategory() function like this:
$scope.subcategory= function() {
//use the selectedItem as you like
console.log($scope.selectedItem.id);
}
In your ng-options you are making use of subcategory whereas in your JS, there is no variable named with subcategory but it's a method.
One cannot simply refer the method, unless it returns the list.
What you actually need is a variable, that contains the object list, that can be looped in the select to get the drop-downs.
Moreover, on using ng-change, you are not passing any id. A better way to do, is to bind the select with a ng-model, on change, you can have a watch on this variable.
You should modify your code somewhat like the following:
HTML:
<select ng-model="someObject.model" ng-options="x.list for x in subcategory"></select>
JS:
$scope.subcategory = ['list:'[{ 'obj1': 'var1' }, { 'obj2': 'var2' }, { 'obj3': 'var3' }]];

Using jQuery to determine an element's class

Most examples I can find showing how to work with attributes show how to set them and not how to retrieve them. In my case, I am trying to get the class of an and then parse it to determine its parent value.
HTML:
<select class='parent' name='parent' size='10'>
<option value='1'>Category 1 -></option>
<option value='2'>Category 2 -></option>
</select>
<select class='child' id='child' size='10'>
<option class='sub_1' value='5'>Custom Subcategory 1.1</option>
<option class='sub_1' value='3'>Subcategory 1.1</option>
<option class='sub_2' value='4'>Subcategory 2.1</option>
</select>
For any given option from the child list, I need to look at the class attribute, parse the name looking for the number (“sub_[n]”) and then grab the value of the option in the parent list.
My code so far (childVal has a value of “5” in my test case):
var class = child.find("option[value=" + childVal + "]").attr("class");
The above class variable is coming back “undefined.” I know the .find is working because I can use it for other things. The problem is getting at the class name.
Once I get the class name, I can strip out the “sub_” to get at the id number.
Is there a better way to do this? Why is .attr(“class”) returning undefined?
Here's a Fiddle link http://jsfiddle.net/n6dZp/8/ to a broken example.
Thank you,
Rick
This is the full function I am working on. It's a cascading select list.
<script type="text/javascript">
function cascadeSelect(parent, child, childVal) {
var childOptions = child.find('option:not(.static)');
child.data('options', childOptions);
parent.change(function () {
childOptions.remove();
child
.append(child.data('options').filter('.sub_' + this.value))
.change();
})
childOptions.not('.static, .sub_' + parent.val()).remove();
if (childVal != '') {
var className = child.find("option[value=" + childVal + "]").attr("class");
** need code here to select the parent and the child options based
on childVal **
}
}
$(function () {
$('.categoryform').find('.child').change(function () {
if ($(this).val() != null) {
$('.categoryform').find('#CategoryId').val($(this).val());
}
});
});
$(function () {
cascadeForm = $('.categoryform');
parentSelect = cascadeForm.find('.parent');
childSelect = cascadeForm.find('.child');
cascadeSelect(parentSelect, childSelect, "5");
});
</script>
class is a reserved word in Javascript, so you can't have a variable with that name. Try
var className = child.find("option[value=" + childVal + "]").attr("class");
Don't use class as a variable name. Kills IE.
This will work but what is child variable equal to?
To obtain the class attribute:
var classAttribute = $('#child').find('option[value="' + childVal + '"]:first').attr('class');
To obtain the 'n' value you can parse the class attribute with a RegEx:
var nValue = /\bsub_([\S]*)\b/.exec( classAttribute )[1];
Hope it helps you.
My apologies, I didn't read your question very carefully at first. Here's my take on what you should do:
var parentVal = $('.child option[value=' + childVal + ']').attr('class').substr(4);
OLD ANSWER
This should do the trick for you:
$(function() {
$('#child').change(function() { $('.parent').val($(this).children(':selected').attr('class').substr(4));
});
});
Here's a live demo: http://jsfiddle.net/n6dZp/
For a start you are missing the $
You need:
var class = $(".child").find("option[value=" + childVal + "]").attr("class");

Categories