How can I create a select DOM object with options in jquery similar to this input creation example?
$('<input />', {
name: 'age',
type: 'number',
placeholder: 'enter a number 1'
}).appendTo('#app');
Is there a way to create it passing attributes?
When creating an element with jQuery, any attribute, or even jQuery method, can be used in the options object, so you can do
$('<select />', {
name : 'test',
on : {
change : function() { /* stuff */ }
},
append : [
$('<option />', {value : "1", text : "Opt 1"}),
$('<option />', {value : "2", text : "Opt 2"}),
$('<option />', {value : "3", text : "Opt 3"})
]
}).appendTo('#app');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="app"></div>
You can create just by passing the entire select with option as string
$('<select name="number">' +
'<option>1</option>' +
'<option>2</option>' +
'<option>3</option>' +
'</select>').appendTo('body');
Another solution, using an array of objects having the required value and text and creating new select element based on the array information.
$(document).ready(function () {
var arrSelect = [
{ value: 1, text: 'One' },
{ value: 2, text: 'Two' },
{ value: 3, text: 'Three' }
];
var select = $('<select>').appendTo('body'); //Create new select element
//Loop through the array of objects and then create new option and append to select element
arrSelect.map(function (arr) { select.append($("<option>").attr('value', arr.value).text(arr.text)) });
$("body").append(select); //Append select to body element
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
1_ you can select Multiple DOM Multi DOM Select
like so :
$( "div, .sCLASS, p.myClass" ).whatever...
2_ you can also select Single DOM with concate Single DOM Select
like so :
$( "p" + ".sCLASS" ).whatever...
BUT you can't pass arg with it
The object select is created and then the options objects are appended.
$('<select />', {
id: 'my-numbers',
name: 'select-number'
})
.append($("<option/>", {
value: '1',
text: 'number1'
}))
.append($("<option/>", {
value: '2',
text: 'number2'
}))
.appendTo('#app');
Related
I am using select2 to select from a list the image that I want to be displayed on the screen.
For this I need to set an attribute on each option: s3_key
I want to put this attribute when the select2 is created
I have seen solutions to add data-* attributes when an option is selected. This solution doesn't work for me because
if the input already has a value selected when loading the web page, the image has to be displayed automatically.
$('#id-gci-main').select2({
language: '<?= getLanguage() ?>',
closeOnSelect: true,
allowClear: true,
placeholder: '',
data: <?= $aJsonGCIsPrincipalesOtorgados ?>
}).on('select2:select', function (e) {
var data = e.params.data;
$(this).children('[value="'+data['id']+'"]').attr({
'data-s3_key':data["s3_key"], //dynamic value from data array
});
}).val(0).trigger('load');
The variable $aJsonGCIsPrincipalesOtorgados has the following structure:
var data = [
{
id: 1,
text: 'xxxx'.
s3_key: '/xx/image.png'
},
Is there any way to do this?
Example code:
https://jsfiddle.net/JorgePalaciosZaratiegui/fhad7gmr/12/
don't do that, simply use a js Object select2data:
const data1 =
[ { id: 'key_1', text: 'YY', s3_key: 'xxxx/yy.png' }
, { id: 'key_2', text: 'BB', s3_key: 'wwww/bb.png' }
, { id: 'key_3', text: 'AAA', s3_key: 'wwww/aaa.png' }
]
const select2data = data1.reduce((r,{id,...more})=>(r[id]=more,r),{})
// console.log( select2data )
$("#id-gci-main").select2(
{ closeOnSelect : true
, allowClear : true
, placeholder : ''
, data : data1
}
).on('change', function(e)
{
console.clear()
console.log( select2data[this.value].s3_key )
});
#id-gci-main {
width : 300px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<select id="id-gci-main" ></select>
I am working on an SPA application where I have a list of data variables that are used as the <option> tags in the dropdown. I want to navigate to another page on the #change event of the dropdown therefore I want to use either the id or name of the select command as the name of the data property. Here is what I mean:
Here is what I have in the data function:
data(){
return {
participants: [
{ value: 0, linkText: '', linkTerm: 'Select' },
{ value: 1, linkText: '/meetings/participants/create', linkTerm: 'Add New' },
{ value: 2, linkText: '/meetings/participants', linkTerm: 'All Participants' },
],
positions: [
{ value: 0, linkText: '', linkTerm: 'Select' },
{ value: 1, linkText: '/meetings/positions/create', linkTerm: 'Add New' },
{ value: 2, linkText: '/meetings/positions', linkTerm: 'All Positions' },
],
}
}
Here is the select tag where I use the above data variables as the <option> tag:
<select name="participants" id="participants" class="select-field" #change="changeRoute($event)">
<option v-for="p in participants" :value="p.value">{{ p.linkTerm }}</option>
</select>
Now I want to have one function changeRoute($event) from which I will navigate to different pages, therefore I want to use the id or name value as the data property, here is the function:
methods:{
changeRoute($event){
var name = $event.target.name;
var value = document.getElementById($event.target.id).value;
}
}
Here in the above function I want to use the name as the data property as below:
I want to write this:
this.name[value].linkText;
And because name here is the name of the tag which is actually participants so the above line of code should mean something like this:
this.participants[value].linkText
And that should return the linkText of the participants object of the data function.
Any help is appreciated in advance.
Change the below line
this.name[value].linkText;
to
this[name][value].linkText;
I intend to build a text with the text of labelField and textfield value
In my fiddle example the text of the fieldLabel is created dynamically.
what I want to achieve is to generate a text with the text of fielLabel and the value of the textfield.
https://fiddle.sencha.com/#fiddle/1icj
As is the fiddle displays "Homer, Simpson"
What I want to achieve: "Name Homer, Last Name Simpson"
It seems to me there is no method which gives the value of fieldLabel.
How to achieve this?
It is possible in some way, using binding?
What if I use a custom property, it is possible to obtain its value?
buttons: [{
text: 'GetValues',
handler: function() {
var formValues = this.up('form').getForm().getValues();
console.log(formValues);
var finalValues = [];
var needsLineBreak = false;
if (formValues != null) {
var form=this.up('form'),
index=0;
Ext.iterate(formValues,function(key,val){
finalValues += form.getComponent(index).getFieldLabel()+':';
finalValues += val + ',';
index++;
});
finalValues=finalValues.slice(finalValues.lenght,-1);
}
console.log(finalValues);
}
}],
you can use getter/setter to achieve this functionality
items: [{
fieldLabel: labelName,
name: 'first',
get value(){
return this.fieldLabel +' Homer';
},
allowBlank: false,
myCustomProp: labelName
},{
fieldLabel: labelLastName,
name: 'last',
get value(){
return this.fieldLabel +' Simpson';
},
allowBlank: false
}],
i am try kendo multiselect tab remove when click on button and again this remove option in come to select.
i have done this code
Close Oranges
<script>
$("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
tagTemplate: "<span class='mitesh12' entity_id ='${data.id}' path ='${data.name}' >" + '#: data.name #' + "</span>",
});
function closeOrange(e){
$("span[entity_id='2']").parent().parent().remove();
}
</script>
this is jsfiddle and i want like this Like
here i am try to remove orange tag and after remove this again i am able to select this orange
help me out this
thanks.
You did not follow the same approach than your second link.
Define the HTML as:
<select id="multiselect" multiple="multiple"></select>
<button id="oranges" class="k-button">Close Oranges</button>
And this code for creating the multiselect:
var multi = $("#multiselect").kendoMultiSelect({
dataSource: [
{ id: 1, name: "Apples" },
{ id: 2, name: "Oranges" }
],
dataTextField: "name",
dataValueField: "id",
tagTemplate: "<span class='mitesh12' entity_id ='${data.id}' path ='${data.name}' >" + '#: data.name #' + "</span>",
}).data("kendoMultiSelect");
The button handler for removing the value is:
$("#oranges").on("click", function(e) {
// List of values to remove (only the ones with id = 2)
var subtract = [2];
var values = multi.value().slice();
values = $.grep(values, function(a) {
return $.inArray(a, subtract) == -1;
});
// Filter out everything
multi.dataSource.filter({});
// Now add the remaining values.
multi.value(values);
});
You can see it here : http://jsfiddle.net/OnaBai/9WfGA/23/
i have two Ext Combo boxes here, i need to change values of second combobox when select event of combobox1 invokes, my problem is i don't know how to change model of a combobox.
items: [{
xtype:'combo',
fieldLabel: 'Course',
afterLabelTextTpl: required,
store: new Ext.data.SimpleStore({
data: [
[1, 'Bsc CS'],
[2, 'MSc CS'],
],
id: 0,
fields: ['value', 'text']
}),
name: 'first',
listeners:{
select: function( combo, records, eOpts )
{
if(this.getValue()=="Bsc CS")
{
// Ext.get('semcombo').getStore.loadData(msc);
}
else if(this.getValue()=="MSc CS")
{
}
}
},
editable:false,
allowBlank: false
},{
xtype:'combo',
fieldLabel: 'Semester',
id : 'semcombo',
afterLabelTextTpl: required,
name: 'last',
allowBlank: false,
}
For the second combobox, configure a combobox for each model type. Hide or show the appropriate combobox as a selection is made in the first combobox.
If you need to change the data completely (JSFiddle)
select: function(checkbox,records) {
comp.clearValue();
comp.bindStore(Ext.StoreMgr.lookup(records[0].data.store));
// you can change the value field if needed
comp.displayField = 'petname';
// you can change the display field if needed
comp.valueField = 'id';
// you can change the display template if needed
comp.displayTpl = new Ext.XTemplate(
'<tpl for=".">' +
'{[typeof values === "string" ? values : values["' + comp.displayField + '"]]}' +
'<tpl if="xindex < xcount">' + comp.delimiter + '</tpl>' +
'</tpl>'
);
comp.picker = null;
}
If you just need to filter (load) the data in second combox you can do something like this
On the select event of the first combobox prepare the second one to filter the data
combobox2.queryData = [{ property: 'fieldName', value: value}];
combobox2.reset();
combobox2.doQuery(combobox.queryData);
where combobox2 is a reference to the activated combo and value a propertyvalue from the combo. To ensure the use of your new query use
combobox2.on('beforequery', function (e) {
e.query = e.combo.queryData;
});