jQuery Create element inside an element - javascript

I've seen many guides online for create a new element in jQuery such as the following code
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).appendTo(someElement);
This creates one input element and appends it. I want to create a div element and add this input element to it and then append it. How would i go about doing that?
Thanks,
Alex

You can use .wrap() to wrap your element into another one before appending it:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).wrap('<div/>').parent().appendTo(someElement);
Note: you'd have to call .parent() because .wrap() does not return the wrapping element
DEMO
You could also do it in several steps if you need to add attributes to the wrapping div, syntax is similar:
var input = $('<input>', { ... });
// create a div element with an ID=wrapper
$('<div/>', { id: 'wrapper' })
// append the input to it
.append(input)
// append the div to "someElement"
.appendTo(someElement);
DEMO

Same syntax, really:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
});
var div = $('<div>', {
id: 'SomeWrapperDiv'
}).append(input);
div.appendTo(someElement);

This maybe help you:
http://jsfiddle.net/Eek7N/1/
var div = $("<div>");
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
});
div.html("I'm the div");
div.append(input);
$("body").append(div);​

And another way:
$('#someElement').append($('<span></span>').append(input));
http://jsfiddle.net/xcZjt/

You can try this.
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
})
$('<div>', {
id: 'divId',
class: 'className'
})
.append(input)
.appendTo(someElement);

Use the wrap function:
var input = $('<input>', {
id: 'FormUsername',
name: 'username',
type: 'text',
value: 'Enter your username...',
focusin: function() {
$(this).val('');
}
}).wrap('<div></div>').parent().appendTo(someElement);
wrap docs:
Description: Wrap an HTML structure around each element in the set of matched elements.

Related

Selectize dropdown within slickgrid is hidden beyond slick grid boundary. How can I make it to come up at top?

I am using selectize to provide inline cell editing in slickgrid. I am able to load this component within cell. But when dropdown options container pops up and it goes beyond the slickgrid viewport, dropdown options container is getting truncated by slickgrid boundary. It should come over the grid. How can I bring the dropdown options container to the top.
var grid;
var columns = [
{ id: 'title', name: 'Title', field: 'title' },
{ id: 'duration', name: 'Duration', field: 'duration' },
{ id: '%', name: '% Complete', field: 'percentComplete' },
{ id: 'start', name: 'Start', field: 'start' },
{ id: 'finish', name: 'Finish', field: 'finish' },
{
id: 'effort-driven',
name: 'Effort Driven',
field: 'effortDriven',
editor: IEditor
},
];
var options = {
enableCellNavigation: true,
enableColumnReorder: false,
editable: true,
autoHeight: true
};
function IEditor(args) {
var selectElement = $('<input type="text"/>');
args.container.append(selectElement[0]);
selectElement.selectize({
create: false,
maxElements: 1,
options: [
{
name: 'A',
value: 'a'
},
{
name: 'B',
value: 'b'
},
{
name: 'C',
value: 'c'
},
{
name: 'D',
value: 'd'
},
{
name: 'E',
value: 'e'
},
{
name: 'F',
value: 'f'
},
],
labelField: 'name',
valueField: 'value'
});
/*********** REQUIRED METHODS ***********/
this.destroy = function() {
// remove all data, events & dom elements created in the constructor
};
this.focus = function() {
// set the focus on the main input control (if any)
};
this.isValueChanged = function() {
// return true if the value(s) being edited by the user has/have been changed
return false;
};
this.serializeValue = function() {
return '';
};
this.loadValue = function(item) {
};
this.applyValue = function(item, state) {
};
this.validate = function() {
return { valid: false, msg: 'This field is required' };
};
}
$(function() {
var data = [];
for (var i = 0; i < 3; i++) {
data[i] = {
title: 'Task ' + i,
duration: '5 days',
percentComplete: Math.round(Math.random() * 100),
start: '01/01/2009',
finish: '01/05/2009',
effortDriven: i % 5 == 0,
};
}
grid = new Slick.Grid('#myGrid', data, columns, options);
grid.init();
});
I have added selectize drop down in Effort Driven column in this plunker
I used to use chosen as my enhanced select but I ran into exactly this problem, and it wasn't solvable due to the HTML it used.
I had to jump ship to Select2. There are examples for this here - check out 'Select2 javascript drop-down editor' and 'Select2 Multiselect javascript drop-down editor'.
Make sure your z-index is bigger than the ones SlickGrid uses. If I remember correctly SlickGrid's highest one was 11 or 12, so with a 13 you should be good to go. Also check the overflow of the cells' css classes; it might happen that your context menu is simply cut off.

How to read values from multiselector component

I am trying to use multiselector from EXTJS 6.5.2
This is the code that I am using to create multiselector with the values that I need
{
xtype: 'multiselector',
title: 'I caktohet:',
name: 'Caktohen[]',
bind: '{userfullname.value}',
fieldName: 'userfullname',
viewConfig: {
deferEmptyText: false,
emptyText: 'Askush i zgjedhur'
},
search: {
field: 'userfullname',
model: 'InTenders.model.UserModel',
store: {
type: 'users',
sorters: 'userfullname',
// proxy: {
// type: 'rest',
// limitParam: null,
// url: 'api/User'
// }
}
}
}
When I call form = win.down('form') records I can get all values except the multiselector values, they show like this on console.
Anyone can help me or guide me how to get the values?
Thank you.
//Code that I'm trying to get multiselector items and save them
saveTenderForm: function (button, e, eOpts) {
var userMultiSelector = Ext.getCmp('AssignedUsers'); //save assigned users
var selectedUsers = userMultiSelector.getStore().getData(); //get store and put them in array
var me = this,
win = button.up('window'),
form = win.down('form'),
// formApplyUpload = this.getFormApplyUpload(),
// var ko = win.items.items[0].items.items[0].value;
recordtenderUsers = Ext.create('InTenders.model.TenderSaveModel');
// recordtenderUsers = form.getRecord();
// record = form.getRecord(),
values = form.getValues();
// appFile = this.getApplicationFile(),
// callbacks;
recordtenderUsers.set(values);
recordtenderUsers.set('tenderUsers',selectedUsers.items);
// // me.showMask();
// if (form.isValid()) {
recordtenderUsers.save({
success: function (recordtenderUsers, operation) {
win.close();
me.hideMask();
},
failure: function (recordtenderUsers, operation) {
me.hideMask();
}
});
You can get value using multiselector.down('grid') this will return you the grid. And grid have method getSelection().
In this FIDDLE, I have created a demo. I hope this will help/guide you to achieve your requirement.
CODE SNIPPET
Ext.application({
name: 'Fiddle',
launch: function () {
Ext.create({
xtype: 'form',
renderTo: Ext.getBody(),
items: [{
xtype: 'multiselector',
title: 'Multi selector example',
fieldName: 'text',
viewConfig: {
deferEmptyText: false,
emptyText: 'No value selected'
},
search: {
field: 'text',
store: {
fields: [{
name: 'text',
type: 'string'
}],
data: [{
text: 'ABC'
}, {
text: 'ABC 1'
}, {
text: 'ABC 2 '
}, {
text: 'ABC 3'
}, {
text: 'ABC 4'
}]
}
}
}, {
xtype: 'button',
text: 'Get Value',
margin:15,
handler: function (btn) {
var multiselector = btn.up('form').down('multiselector');
if (multiselector.down('grid')) {
multiselector.down('grid').getSelection().forEach(rec => {
console.log(rec.get('text'));
});
}
}
}]
});
}
});

How to enable Extjs filters on page load

I want to filter my grid with different buttons that active certain filters. However they do not work on page load. Only when you select/deselect a filter option and then click the button, does the filter actually kick in.
When the page first loads and you click a button, you get the following error:
TypeError: filter is undefined
How do I enable these filter settings when the page first loads?
To recreate the error. Load the fiddle and try clicking the buttons and notice they don't work. Then activate one of the filters and try again. The buttons will work after a filter is activated.
Fiddle
Buttons
var openButton = Ext.create('Ext.Button', {
text: 'Open Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Open/Current');
}
});
var holdButton = Ext.create('Ext.Button', {
text: 'On Hold Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Hold');
}
});
var closedButton = Ext.create('Ext.Button', {
text: 'Closed Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
filter.setActive(true);
filter.setValue('Archived/Closed');
}
});
Columns
columns: [{
text: 'Title',
width: 260,
dataIndex: 'Title',
filterable: true,
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
text: 'Description',
flex: 1,
dataIndex: 'Description',
filter: {
type: 'string'
// specify disabled to disable the filter menu
//, disabled: true
}
}, {
text: 'Modified',
width: 90,
dataIndex: 'Modified',
xtype: 'datecolumn',
format: 'm/d/Y',
filter: true
}, {
text: 'Status',
width: 100,
dataIndex: 'TopicStateValue',
filter: {
active: true,
type: 'list',
value: 'Open/Current',
options: ['Open/Current', 'Archived/Closed', 'Hold']
}
}]
Just check if the filter exists before pass value to it, if not, add it like this:
var openButton = Ext.create('Ext.Button', {
text: 'Open Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Open/Current');
}
});
var holdButton = Ext.create('Ext.Button', {
text: 'On Hold Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Hold');
}
});
var closedButton = Ext.create('Ext.Button', {
text: 'Closed Topics',
handler: function () {
var filter = grid[uniqueId].filters.getFilter('TopicStateValue');
if (!filter) {
filter = grid[uniqueId].filters
.addFilter({
type : 'string',
dataIndex : 'TopicStateValue'
});
}
filter.setActive(true);
filter.setValue('Archived/Closed');
}
});
You need to initialize the filters manually before you use them.
Please add the below code to your grid panel.
listeners: {
beforeRender:function() {
this.filters.createFilters();
}
},
I tried that on your fiddle and it works.

Event to some dynamically generated checkbox issue

My english is not good but I need help please!!!
I am dynamically adding rows to a table, add textbox and checkbox's.
In the change function I want: When the first checkbox is marked the others are disabled and the texbox change their value
The updatebox function It works perfectly for each generated row, but change function only it works with the first.
function agregar() {
var fila = $('<tr></tr>');
var columna = $('<td></td>');
var input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list1'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb2'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list2'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb3'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list3'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb4'
});
columna.append(input);
input = $('<input type="text" />').attr({
name: 'idiomas_usu[]',
id: 'list4'
});
columna.append(input);
input = $('<input type="checkbox" />').attr({
name: 'dos',
class: 'cb2',
id: 'cb5'
});
columna.append(input);
fila.append(columna);
$('#tab_logic').append(fila);
}
function updateBox(event) {
var input = $(this).prev();
if (this.checked) {
input.val("1");
} else {
input.val("");
}
}
function change(event) {
var $this = $(this);
if ($this.is("#cb2")) {
if ($("#cb2:checked").length > 0) {
$("#cb3").prop({
disabled: true,
checked: false
});
$("#cb4").prop({
disabled: true,
checked: false
});
$("#cb5").prop({
disabled: true,
checked: false
});
$("#list2").prop({
disabled: true,
value: ''
});
$("#list3").prop({
disabled: true,
value: ''
});
$("#list4").prop({
disabled: true,
value: ''
});
} else {
$("#cb3").prop("disabled", false);
$("#cb4").prop("disabled", false);
$("#cb5").prop("disabled", false);
}
}
}
$('#boton').click(agregar);
$('#tab_logic').on('click', '.cb2', updateBox);
$('#tab_logic').on('click', '.cb2', change);
Here's the code running: JSfiddle
Please help me!!!!
You have all the same IDs so its grabbing the first occurrence. One option is to give your rows an ID and use that in your jQuery selector to target the correct items, like this: https://jsfiddle.net/rko41z88/8/
Below is a snippet of the fiddle, go to the fiddle to see the whole thing in action.
Give your rows an ID in your agregar() function like this...
window.myRowCnt = window.myRowCnt+1;
var fila = $('<tr id="row'+window.myRowCnt+'"></tr>');
Then use that row ID to target the correct items like this...
function change(event){
var $this = $(this);
var rowId = $this.closest('tr')[0].id;
if ($this.is("#cb2")) {
if ($("#"+rowId+" #cb2:checked").length > 0) {
$("#"+rowId+" #cb3").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb4").prop({ disabled: true, checked: false });
$("#"+rowId+" #cb5").prop({ disabled: true, checked: false });
$("#"+rowId+" #list2").prop({ disabled: true, value: '' });
$("#"+rowId+" #list3").prop({ disabled: true, value: '' });
$("#"+rowId+" #list4").prop({ disabled: true, value: '' });
} else {
$("#"+rowId+" #cb3").prop("disabled", false);
$("#"+rowId+" #cb4").prop("disabled", false);
$("#"+rowId+" #cb5").prop("disabled", false);
}
}
}
This might not be the best answer for you, but I recommend to use React.js framework. It's best for dynamic web applications.

ckeditor plugin dialog select get the description from the selected one

Im am developing a placeholder plugin to CKEDITOR and it´s basically complete. The problem I have is that I am trying to get the value and description from the select within the dialog and I am only getting the value.
The array that contains the description and value looks like this
-->
items: [['description1', 'value1'], ['description2', 'value2']] <--
In the return -> contents -> elements with ID dropdown I have setup and commit function. In these functions I need to get the description just like getting the name from select option.
Really need help with this one, thanks in advance
example -->
<select>
<option value="value1">description1</option>
<option value="value2">description2</option>
</select>
example <--
(function () {
function placeholderDialog(editor, isEdit) {
var lang = editor.lang.phlink,
generalLabel = editor.lang.common.generalTab;
return {
title: lang.title,
minWidth: 300,
minHeight: 80,
contents: [
{
id: 'info',
label: generalLabel,
title: generalLabel,
elements: [
{
id: 'dropdown'
, type: 'select'
, label: lang.chooseVal
, 'default': 'Detta är default'
, items: [['description1', 'value1'], ['description2', 'value2']]
, setup: function (data) {
// need the description
this.setValue(data.title);
}
, commit: function (data) {
// need the description
data.title = this.getValue();
}
},
{
id: 'text',
type: 'text',
style: 'width: 100%;',
label: lang.text,
'default': '',
required: true,
validate: CKEDITOR.dialog.validate.notEmpty(lang.textMissing),
setup: function (data) {
this.setValue(data.text);
},
commit: function (data) {
data.text = this.getValue();
}
}
]
}
],
onShow: function () {
var data = { tag: 'link', content: "detta är innehåll", title: "Länk till svar", text: "detta är text" };
if (isEdit) {
this._element = CKEDITOR.plugins.phlink.getSelectedPlaceHolder(editor);
data.title = this._element.getAttribute('title');
data.text = this._element.getText();
data.tag = this._element.getAttribute('data-jztag');
}
this.setupContent(data);
},
onOk: function () {
var data = { tag: 'link', content: null, title: null, text: null };
this.commitContent(data);
CKEDITOR.plugins.phlink.createPlaceholder(editor, this._element, data);
delete this._element;
}
};
}
CKEDITOR.dialog.add('createplaceholder', function (editor) {
return placeholderDialog(editor);
});
CKEDITOR.dialog.add('editplaceholder', function (editor) {
return placeholderDialog(editor, 1);
});
})();
Use the following to get option's text:
var input = this.getInputElement().$;
console.log( input.options[ input.selectedIndex ].text );
>> "description1"

Categories