Javascript / jQuery Hide fields based on Selected Drop Down item - javascript

I have some code that I have created for an OnChange event which works perfectly.
<script type="text/javascript">
function UpdEventChanged(selectEl) {
var text = selectEl.options[selectEl.selectedIndex].text;
if (text == "Sickness" || text == "Holiday") {
$("input[id$=eventPostCode").hide();
$("#ContentPlaceHolder1_LBLUpdPCReq").hide();
$("#ContentPlaceHolder1_lblUpdPC").hide();
}
else {
$("input[id$=eventPostCode").show();
$("#ContentPlaceHolder1_LBLUpdPCReq").show();
$("#ContentPlaceHolder1_lblUpdPC").show();
}
}
</script>
I need to integrate the above code to make it work on the Page Load event. Here is my code:
// update Dialog
$('#updatedialog').dialog({
autoOpen: false,
width: 500,
buttons: {
"update": function() {
//alert(currentUpdateEvent.title);
var eventToUpdate = {
id: currentUpdateEvent.id,
//title: $("#eventName").val(),
title: $("#EventSalesPerson option:selected").text(),
description: $("#eventDesc").val(),
salesperson: $("#EventSalesPerson option:selected").text(),
eventPostCode: $("input[id$=eventPostCode]").val(),
eventname: $("#EventEventName option:selected").text()
};
{
PageMethods.UpdateEvent(eventToUpdate, updateSuccess);
$(this).dialog("close");
currentUpdateEvent.title = $("#eventName").val();
currentUpdateEvent.description = $("#eventDesc").val();
currentUpdateEvent.salesperson = $("#EventSalesPerson option:selected").text();
currentUpdateEvent.eventname = $("#EventEventName option:selected").text();
currentUpdateEvent.eventPostCode = $("input[id$=eventPostCode]").val();
$('#calendar').fullCalendar('updateEvent', currentUpdateEvent);
location.reload(true);
}
},
"delete": function() {
if (confirm("do you really want to delete this event?")) {
PageMethods.deleteEvent($("#eventId").val(), deleteSuccess);
$(this).dialog("close");
$('#calendar').fullCalendar('removeEvents', $("#eventId").val());
}
}
}
});
If #EventEventName selected text = Holiday or Sickness then I need the following items to be hidden:
"input[id$=eventPostCode"
"#ContentPlaceHolder1_LBLUpdPCReq"
"#ContentPlaceHolder1_lblUpdPC"
And obviously if they are not selected then the above should be displayed.
Thanks

It looks like you need something about like this:
var EventEventNameText = $('#EventEventName').val();
if (EventEventNameText=='Holiday' || EventEventNameText=='Sickness') {
$('#eventPostCode').hide();
$('#ContentPlaceHolder1_LBLUpdPCReq').hide();
$('#ContentPlaceHolder1_lblUpdPC').hide();
}
Let me know how that works for you.

Related

customise odoo12 JavaScript file

I want to replace the functionality of the js file. As we have widget many2many in relation_field.js in that there is one function search, that contains code for creating and edit option. I want to change this functionality as per my needs. Following is the main code that I want to change
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
return self._searchCreatePopup("form", false, self._createContext(search_val));
};
values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (values.length === 0) {
values.push({
label: _t("No results to show..."),
});
}
following is my code. I want to add an alert function to create and edit the option of many2many fields. For that, I have use alert function.
odoo.define('survey_inherit.create_record',function(require){
"use strict";
console.log("In js file");
var relationalField = require('web.relational_fields');
var FieldMany2One = relationalField.FieldMany2One.include({
_search: function (search_val) {
var create_enabled = self.can_create && !self.nodeOptions.no_create;
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
**alert(‘Test’);**
//return self._searchCreatePopup("form", false, self._createContext(search_val));
};
this.values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (this.values.length === 0) {
this.values.push({
label: _t("No results to show..."),
});
}
}
});
});
can any one please help or any other suggestion.
Thanks in advance.
I suggest you to remove assigning your code to FieldMany2One variable.
So code will be:
odoo.define('survey_inherit.create_record',function(require){
"use strict";
console.log("In js file");
var relationalField = require('web.relational_fields');
relationalField.FieldMany2One.include({
_search: function (search_val) {
var create_enabled = self.can_create && !self.nodeOptions.no_create;
if (create_enabled && !self.nodeOptions.no_create_edit) {
var createAndEditAction = function () {
// Clear the value in case the user clicks on discard
self.$('input').val('');
**alert(‘Test’);**
//return self._searchCreatePopup("form", false, self._createContext(search_val));
};
this.values.push({
label: _t("Create and Edit..."),
action: createAndEditAction,
classname: 'o_m2o_dropdown_option',
});
} else if (this.values.length === 0) {
this.values.push({
label: _t("No results to show..."),
});
}
}
});
});

ExtJS: How to pass keystrokes from text field to Grid?

I have following grid declaration:
quickSearchGrid = Ext.create('Ext.grid.Panel', {
height: 500,
collapsible: true,
.....
Then, I have input element above it:
<input type="text" id="quickSearch" value="Search" style="height: 25px; width: 100%;" />
I want to pass specific keystrokes - Up, Down, PgUp, PgDown etc from input to grid. So that when user has focus in text field, he'll be able to navigate in the grid with keyboard.
What I'm trying is creating my own KeyNav:
var nav = Ext.create('Ext.util.KeyNav', Ext.get('quickSearch'), {
scope: Ext.get('quickSearch'),
down: function (e) {
console.log(e)
quickSearchGrid.fireEvent('keydown', quickSearchGrid, e)
}
});
Function is being called (it writes to console) but grid does not react.
Found a workaround you could use. Create the text input in extJs instead of declaring it in html:
var quickSearch = Ext.create('Ext.form.field.Text', {
id: 'quickSearch',
name: 'quickSearch',
fieldLabel: 'QuickSearch',
allowBlank: true
});
You can then use it for navigation in the grid with arrows by selecting a record with index 1 higher/lower than the one currently selected:
var grid = quickSearchGrid;
var view = quickSearchGrid.getView();
var nav = Ext.create('Ext.util.KeyNav', Ext.getDoc(), {
down: function(e) {
var selectionModel = grid.getSelectionModel();
var select = 0; // select first if no record is selected
if ( selectionModel.hasSelection() ) {
select = grid.getSelectionModel().getSelection()[0].index + 1;
}
view.select(select);
quickSearch.focus(); // to get focus back to the input
},
up: function(e) {
var selectionModel = grid.getSelectionModel();
var select = grid.store.totalCount - 1; // select last element if no record is selected
if ( selectionModel.hasSelection() ) {
select = grid.getSelectionModel().getSelection()[0].index - 1;
}
view.select(select);
quickSearch.focus(); // to get focus back to the input
},
});
With ExtJS 6, it was really easy to simulate navigation with bufferedRenderer.scrollTo() method:
Here, I'm creating KeyNav but you can rewrite it to pure Javascript/jQuery:
quickSearchKeyNav = Ext.create('Ext.util.KeyNav', Ext.get('quickSearch'), {
scope: Ext.get('quickSearch'),
up: function (e) {
quickSearchGrid.view.bufferedRenderer.scrollTo(
quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) - 1,
true);
},
pageUp: function (e) {
var rowsOnScreen = quickSearchGrid.getNavigationModel().getRowsVisible();
quickSearchGrid.view.bufferedRenderer.scrollTo(
quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) - rowsOnScreen,
true);
},
pageDown: function (e) {
var rowsOnScreen = quickSearchGrid.getNavigationModel().getRowsVisible();
quickSearchGrid.view.bufferedRenderer.scrollTo(
quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) + rowsOnScreen,
true);
},
down: function (e) {
quickSearchGrid.view.bufferedRenderer.scrollTo(
quickSearchGrid.getStore().indexOf(quickSearchGrid.getSelection()[0]) + 1,
true);
}
});

How do I make tinyMCE editor stay in my jQgrid textarea formedit form after first initialize?

I have a jqgrid that I am trying to use tinyMCE in the text area to send/store html in my database and reload to my grid. I have a custom column with tinyMCE for the text area but after I open editform once and close it next time it is opened tinymce does not initialize and a regular textarea appears. (Also when url modal it looses focus and focuses on editform. The text is pasted to the back "Project" field instead(picture below).)What I'm I doing wrong?
Reason why my TineMCE "Links" was losing focus was because of a simple syntax error. I had modal:true in the editgrid code.
UPDATE FOR WORKING INLINE EDIT IMPLEMENTATION
Here are examples for correct implementation for inline edit(Thank you #Oleg): DEMO1 | DEMO2
INLINE EDIT WORKING CODE SAMPLE:
{ name: "note", width: 260, sortable: false, editable: true,
//edittype: "textarea"
edittype:'custom',
editoptions: {
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
},
custom_value: function (element, oper, gridval) {
var id;
if (element.length > 0) {
id = element.attr("id");
} else if (typeof element.selector === "string") {
var sels = element.selector.split(" "),
idSel = sels[sels.length - 1];
if (idSel.charAt(0) === "#") {
id = idSel.substring(1);
} else {
return "";
}
}
if (oper === "get") {
return tinymce.get(id).getContent({format: "row"});
} else if (oper === "set") {
if (tinymce.get(id)) {
tinymce.get(id).setContent(gridval);
}
}
}}
}
jqGrid column:
<script src="js/jquery-1.9.0.min.js" type="text/javascript"></script>
<script src="js/i18n/grid.locale-en.js" type="text/javascript"></script>
<script src="js/jquery.jqGrid.min.js" type="text/javascript"></script>
<script src="js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.js"></script>
<script src="tinymce/tinymce.min.js"type="text/javascript"></script>
<script src="tinymce/jquery.tinymce.min.js"type="text/javascript"></script>
<script src= "tinymce/plugins/link/plugin.min.js" type="text/javascript"></script>
<script type="text/javascript">
...
{ name:'notes',
index:'notes',
edittype:'custom', editable:true,
editoptions:{
"custom_element":function( value , options) {
var elm = $('<textarea></textarea>');
elm.val( value );
// give the editor time to initialize
setTimeout( function() {
tinymce.init({selector: "textarea#notes",plugins: "link"});
}, 100);
return elm;
},
"custom_value":function( element, oper, gridval) {
if(oper === 'get') {
return tinymce.get('notes').getContent({format: 'row'});
} else if( oper === 'set') {
if(tinymce.get('notes')) {
tinymce.get('notes').setContent( gridval );
}
}
}}}
Try to replace the code of custom_element to the following
custom_element: function (value, options) {
var elm = $("<textarea></textarea>");
elm.val(value);
// give the editor time to initialize
setTimeout(function () {
try {
tinymce.remove("#" + options.id);
} catch(ex) {}
tinymce.init({selector: "#" + options.id, plugins: "link"});
}, 50);
return elm;
}
One more simpel

Cannot select a dynamically added list item until it is clicked

I have written a small JQuery plugin that creates a dropdown box based on bootstrap. I have written it to where a data attribute supplies a url that produces the list items. After the ajax call, Jquery loops through the list items and inserts them into the dropdown menu. Here is what I do not understand, the plugin takes a div with the class of .combobox and appends the required html to make the combobox. It uses two functions, _create() and _listItems(). _create() actually adds the html and calls on _listItems() to make the ajax call and it returns the list items to be appended. Looks like this:
;(function ( $, window, document, undefined ) {
var Combobox = function(element,options) {
this.$element = $(element);
this.$options = $.extend({}, $.fn.combobox.defaults, options);
this.$html = {
input: $('<input type="text" placeholder="[SELECT]" />').addClass('form-control'),
button: $('<div id="test"/>').addClass('input-group-btn')
.append($('<button />')
.addClass('btn btn-default input-sm')
.append('<span class="caret"></span>'))
}
this.$list_type = this.$element.attr('data-type');
this.$url = this.$element.attr('data-url');
this.$defaultValue = this.$element.attr('data-default');
this._create();
this.$input = this.$element.find('input');
this.$button = this.$element.find('button');
this.$list = this.$element.find('ul')
this.$button.on('click',$.proxy(this._toggleList,this));
this.$element.on('click','li',$.proxy(this._itemClicked,this));
this.$element.on('mouseleave',$.proxy(this._toggleList,this));
if(this.$defaultValue) {
this.selectByValue(this.$defaultValue);
}
}
Combobox.prototype = {
constructor: Combobox,
_create: function() {
this.$element.addClass('input-group input-group-sm')
.append(this.$html.input)
.append(this._listItems())
.append(this.$html.button);
},
_itemClicked: function(e){
this.$selectedItem = $(e.target).parent();
this.$input.val(this.$selectedItem.text());
console.log(this.$element.find('[data-value="W"]'))
this._toggleList(e);
e.preventDefault();
},
_listItems: function() {
var list = $('<ul />').addClass('dropdown-menu');
$.ajax({
url: this.$url,
type: 'POST',
data: {opt: this.$list_type},
success:function(data){
$.each(data,function(key,text){
list.append($('<li class="listObjItem" data-value="'+text.id+'">'+text.value+'</li>'));
})
}
})
return list
},
selectedItem: function() {
var item = this.$selectedItem;
var data = {};
if (item) {
var txt = this.$selectedItem.text();
data = $.extend({ text: txt }, this.$selectedItem.data());
}
else {
data = { text: this.$input.val()};
}
return data;
},
selectByValue: function(value) {
var selector = '[data-value="'+value+'"]';
this.selectBySelector(selector);
},
selectBySelector: function (selector) {
var $item = this.$element.find(selector);
if (typeof $item[0] !== 'undefined') {
this.$selectedItem = $item;
this.$input.val(this.$selectedItem.text());
}
else {
this.$selectedItem = null;
}
},
enable: function () {
this.$input.removeAttr('disabled');
this.$button.children().removeClass('disabled');
this.$button.on('click',$.proxy(this._toggleList,this));
},
disable: function () {
this.$input.attr('disabled', true);
this.$button.children().addClass('disabled');
this.$button.off('click',$.proxy(this._toggleList,this));
},
_toggleList: function(e) {
if(e.type == 'mouseleave') {
if(this.$list.is(':hidden')) {
return false;
} else {
this.$list.hide();
}
} else {
this.$list.toggle();
e.preventDefault();
}
}
}
$.fn.combobox = function (option) {
return this.each(function () {
if (!$.data(this, 'combobox')) {
$.data(this, 'combobox',
new Combobox( this, option ));
}
});
};
$.fn.combobox.defaults = {};
$.fn.combobox.Constructor = Combobox;
})( jQuery, window, document );
The problem is that after the items are appended to the DOM, everything is selectable accept the list items. I currently have an .on() statement that binds the click event with the list item. To test this out I have used console.log(this.$element.find('[data-value="W"]') and it does not return an element, however if I place that same console log in the click callback of the list item it will return the element and it is selectable. Am I doing something wrong?
EDIT
I have pasted the entire plugin to save on confusion.

Dynamically add UI Elements in CKEditor Dialog

I'm trying to trigger a callback to dynamically populate a CKEditor dialog with checkboxes when the dialog is opened. I've read other solutions that use iframes, but this won't work for me because the dialog needs to be populated based on other elements on the same page.
Here is what I have so far. There are no errors, but the dialog is just empty when it opens. I expect the addContents function to fill in the dialog. I've confirmed that dialog.definition.contents does include the contents and elements that I want, but it's just not filling in the actual dialog. What am I missing?
(function() {
CKEDITOR.plugins.add( 'embeds', {
icons: 'embed',
init: function(editor) {
var self = this,
elements = [];
CKEDITOR.dialog.add('EmbedsDialog', function (instance) {
return {
title : 'Embeds',
minWidth : 550,
minHeight : 200,
contents: [],
onShow: function() {
var dialog = this,
elements = [];
$('#embeds-fields tr').each(function() {
var title = $(this).find('input[type=text]').val(),
url = $(this).find('input[type=url]').val();
if(url != "") {
elements.push({
label : "embed",
title : url,
type : 'checkbox'
});
}
});
dialog.definition.removeContents('embeds');
dialog.definition.addContents({
id : 'embeds',
expand : true,
elements : elements
});
},
}; // return
});
editor.addCommand('Embeds',
new CKEDITOR.dialogCommand('EmbedsDialog', {
allowedContent: 'a[*](*)'
})
);
editor.ui.addButton('Embeds', {
label : 'Embeds',
command : 'Embeds',
toolbar : 'embeds'
});
} // init
}); // add
})(); // closure
Based off of this example, I ended up with this solution, where "main" is the ID of the original content.
CKEDITOR.on('dialogDefinition', function(ev) {
var dialogName = ev.data.name;
var dialogDefinition = ev.data.definition;
if (dialogName == 'EmbedsDialog') {
var main = dialogDefinition.getContents('main');
$('#embeds-fields tr').each(function() {
var title = $(this).find('input[type=text]').val(),
url = $(this).find('input[type=url]').val();
if(url != "") {
main.add({
type : 'checkbox',
label : title,
});
}
});
}
});

Categories

Resources