Extjs reset filefield input - javascript

How reset filefield input in ExtJS? I am trying:
//this - point on Ext.panel.Form
var form = this.getForm();
form.reset();
var filefield = this.getForm().getFields().get(0);
filefield.reset();
filefield.setValue('');
filefield.value = '';
But not one of these methods don't work. Thank you for help!

Use below code will help you
function clearFileUpload(id){
// get the file upload element
fileField = document.getElementById(id);
// get the file upload parent element
parentNod = fileField.parentNode;
// create new element
tmpForm = document.createElement("form");
parentNod.replaceChild(tmpForm,fileField);
tmpForm.appendChild(fileField);
tmpForm.reset();
parentNod.replaceChild(fileField,tmpForm);
}

Old post, but I encountered this problem as well, and I found a cleaner solution.
First of all make sure , the filefield has allowBlank: true set.
Then you can call the setRawValue method as so :
filefield.setRawValue("");

The easiest way that you might be looking for would be :
filefield.fileInputEl.dom.value = '';

Based on this answer: HTML input file selection event not firing upon selecting the same file
In Ext.ux.form.FileUploadField component add the following code in the change event under the bindListeners function.
var that = this;
setTimeout(function() {
that.fileInput.dom.value = null;
that.setValue(that.fileInput.dom.value);
}, 100);
bindListeners: function(){
this.fileInput.on({
scope: this,
mouseenter: function() {
this.button.addClass(['x-btn-over','x-btn-focus'])
},
mouseleave: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
mousedown: function(){
this.button.addClass('x-btn-click')
},
mouseup: function(){
this.button.removeClass(['x-btn-over','x-btn-focus','x-btn-click'])
},
change: function(){
var v = this.fileInput.dom.value;
this.setValue(v);
this.fireEvent('fileselected', this, v);
var that = this;
setTimeout(function() {
that.fileInput.dom.value = null;
that.setValue(that.fileInput.dom.value);
}, 100);
}
});
},

Related

Make field invisible via js code - ODOO 9

I'm looking for a method which makes a field invisible on js (i'm making a custom widget 'InvisibleIfEmptry').
I tried to override _check_visibility method when extending FormWidget.AbstractField class :
var core = require('web.core'),
form_common = require('web.form_common');
var InvisibleIfEmpty = form_common.AbstractField.extend({
start: function() {
this.on("change:effective_readonly", this, function() {
this._toggle_label();
this._check_visibility();
});
this.render_value();
this._toggle_label();
},
_check_visibility: function() {
if (this.get("effective_readonly"))
this.$el.toggleClass('o_form_invisible',true);
}
this.$el.toggleClass('o_form_invisible',false);
}
}, .....
but this makes invisible only the field's value, not the label.
my guess is to alter some of field_manager's values but i can't figure out which one ?
Thank you for your help :)
Here is my JS code for doing that :
odoo.define('myCustomModule', function(require)
{
'use strict';
var core = require('web.core'),
form_common = require('web.form_common'),
form_view = require('web.FormView');
form_common.AbstractField.include({
start: function() {
this._super();
// Check visibility logic below when content
// changes or the form swich to view mode
this.field_manager.on("view_content_has_changed", this, function() {
this._check_visibility();
});
this.on("change:effective_readonly", this, function() {
this._toggle_label();
this._check_visibility();
});
},
_check_visibility: function() {
// If the form is in view mode and the field is empty,
// make the field invisible
window.alert(this.);
if (this.field_manager.get("actual_mode") === "view" ) {
if(this.get("value") == false){
this.$el.toggleClass('o_form_invisible',true);
this.$label.toggleClass('o_form_invisible',true);
}else{
this.$el.toggleClass('o_form_invisible',this.get("effective_invisible"));
this.$label.toggleClass('o_form_invisible',this.get("effective_invisible"));
}
}else{
this.$el.toggleClass('o_form_invisible',this.get("effective_invisible"));
this.$label.toggleClass('o_form_invisible',this.get("effective_invisible"));
}
},
});
});
But this applies to all my modules.
Does Any one know how to get module/model name from AbstractField ?

Can a JQuery plugin be called on a JQuery chain of methods or does it need to be called straight after a selector?

I'm having difficulty getting my textarea to expand vertically automatically.
I have some code to help make textarea auto expand vertically and for some reason it works when I clean out all my JS and provide a selector with reference to textarea e.g. $('textarea').autoGrow();
Calling the plugin on a chain of methods stops it from working. E.G.
micropostBox.hide().removeClass("micropost_content")
.addClass("micropost_content_expanded").show().autoGrow();
I established the plugin code works so copied all my working code to the same page and applied the autoGrow code to my textarea but it seems to be unresponsive. I noticed that the plugin I'm using the code from uses bind and unbind methods. In my code I use on and off methods from JQuery and wondering if this could be why the auto resizing of my textarea is not working?
Here is the code:
http://jsfiddle.net/erU5J/101/
autogrow plugin js code
$(function($) {
$.fn.autoGrow = function() {
return this.each(function() {
var txtArea = $(this);
var colsDefault = txtArea.attr('cols');
var rowsDefault = txtArea.attr('rows');
var updateSize = function() {
var linesCount = 0;
var lines = txtArea.attr('value').split('\n');
for (var i = lines.length - 1; i >= 0; --i) {
linesCount += Math.floor((lines[i].length / colsDefault) + 1);
}
if (linesCount >= rowsDefault) {
txtArea.attr('rows', linesCount + 1);
}
else {
txtArea.attr('rows', rowsDefault);
}
};
txtArea.unbind('.autoGrow').bind('keyup.autoGrow', updateSize).bind('keydown.autoGrow', updateSize).bind('change.autoGrow', updateSize);
});
};
});
my js code
$(function() {
$("div.microposts").on("focus", "textarea#micropostBox", function() {
var micropostForm = $(this).parent(),
micropostBox = micropostForm.find('textarea#micropostBox'),
micropostButton = micropostForm.find("input#micropostButton"),
xButton = micropostForm.find("div.xButton");
micropostBox.prop('rows', 7);
micropostForm.find('div#micropostOptions').removeClass('micropostExtraOptions');
micropostForm.find('div#postOptions').show();
$.trim(micropostBox.val()) == '' ? micropostButton.addClass("disabledMicropostButton").show()
:
micropostButton.prop('disabled', false);
micropostBox.hide().removeClass("micropost_content").addClass("micropost_content_expanded").show().autoGrow();
xButton.show();
micropostButton.prop('disabled', true);
micropostBox.off().on("keypress input change", function() {
micropostButton.prop({
disabled: !$.trim($(this).val()) != ''
});
$.trim($(this).val()) != '' ? micropostButton.removeClass("disabledMicropostButton").addClass("activeMicropostButton")
:
micropostButton.removeClass("activeMicropostButton").addClass("disabledMicropostButton");
});
xButton.on('click', function() {
micropostBox.removeClass("micropost_content_expanded").addClass("micropost_content");
micropostForm.find('div#micropostOptions').addClass('micropostExtraOptions');
micropostBox.val("");
micropostForm.find('div#postOptions').hide();
xButton.hide();
micropostButton.hide();
micropostBox.removeAttr('style');
micropostBox.prop('rows', 0);
micropostForm.find('.imagePreview > img').remove();
micropostForm.find('.imagePreview').hide();
});
});
});
$(function() {
$('div.microposts').on('click', 'li#addImage', function() {
var form = $(this).parents('form#new_micropost'),
fileField = form.find('input#micropost_image');
fileField.trigger('click');
});
});
$(function() {
$('input#micropost_image').change(function(evt) { //.off() make sautoresize work
var image = evt.target.files[0],
form = $(this).parents('form#new_micropost'),
imagePreviewBox = form.find('div.imagePreview'),
reader = new FileReader();
reader.onload = function(evt) {
var resultdata = evt.target.result,
img = new Image();
img.src = evt.target.result;
imagePreviewBox.show().prepend(img);
};
reader.readAsDataURL(image);
});
});​
textarea
<textarea class="micropost_content" cols="40" id="micropostBox" name="micropost[content]" placeholder="" rows="0"></textarea>
It would be best to view a working example on jsfiddle. My aim is to have the auto resizing of textarea working before and after an image is added to the page using the image upload button in the textarea.
Kind regards
It depends if the method preceding the plugin call returned the jQuery object containing the elements to where the plugins need to be attached.
Here are a few examples of methods that do and do not return the elements you started with:
$('element') //get an element
.contents() //get an elements contents
.wrapAll('<div>') //wrapAll contents with div and returns the contents, not wrapper
.parent() //the wrapper
.parent() //the element
.myPlugin() //we attach a plugin to element
$('<div>')
.appendTo('body') //appendTo returns the same element, the div
.myPlugin() //attaches to the div
$('element') //get an element
.text() //get its text
.myPlugin() //chaining isn't possible since text() returns a string
Better read the docs for every method in jQuery and what it returns. Some DOM methods usually return the same element, some don't, and some don't return elements but values.
In summary, can plugins be attached after chains? YES, and it depends.
Refer to the jQuery's documentation
http://docs.jquery.com/Plugins/Authoring#Maintaining_Chainability

setTimeout("this.disabled=false",3000); is not working

I am trying to prevent duplicated data to database when the user click the submit button multiple times within a very short time (eg double click speed). First I disable the button after one click, then enable the button again after 3 seconds. I don't know why setTimeout("this.disabled=false",3000); is not working on jquery. Please help me out, below is my codes :
$(function() {
$(".btnSendResp").click(function() {
this.disabled = true;
setTimeout("this.disabled=false",3000);
postinResp();
});
});
You have the wrong this.
You need to save a reference to this in a local variable, then pass a function to setTimeout that uses the variable.
For example:
var self = this;
setTimeout(function() {
self.disabled = false;
}, 3000);
$(function() {
$(".btnSendResp").click(function() {
var that = this;
that.disabled = true;
setTimeout(function(){
that.disabled=false;
},3000);
postinResp();
});
});

Create a jQuery special event for content changed

I'm trying to create a jQuery special event that triggers when the content that is bound, changes. My method is checking the content with a setInterval and check if the content has changed from last time. If you have any better method of doing that, let me know. Another problem is that I can't seem to clear the interval. Anyway, what I need is the best way to check for content changes with the event.special.
(function(){
var interval;
jQuery.event.special.contentchange = {
setup: function(data, namespaces) {
var $this = $(this);
var $originalContent = $this.text();
interval = setInterval(function(){
if($originalContent != $this.text()) {
console.log('content changed');
$originalContent = $this.text();
jQuery.event.special.contentchange.handler();
}
},500);
},
teardown: function(namespaces){
clearInterval(interval);
},
handler: function(namespaces) {
jQuery.event.handle.apply(this, arguments)
}
};
})();
And bind it like this:
$('#container').bind('contentchange', function() {
console.log('contentchange triggered');
});
I get the console.log 'content changed', but not the console.log 'contentchange triggered'. So it's obvious that the callback is never triggered.
I just use Firebug to change the content and to trigger the event, to test it out.
Update
I don't think I made this clear enough, my code doesn't actually work. I'm looking for what I'm doing wrong.
Here is the finished code for anyone interested
(function(){
var interval;
jQuery.event.special.contentchange = {
setup: function(){
var self = this,
$this = $(this),
$originalContent = $this.text();
interval = setInterval(function(){
if($originalContent != $this.text()) {
$originalContent = $this.text();
jQuery.event.handle.call(self, {type:'contentchange'});
}
},100);
},
teardown: function(){
clearInterval(interval);
}
};
})();
Thanks to Mushex for helping me out.
also take a look to James similar script (declaring as jquery object method and not as event)
jQuery.fn.watch = function( id, fn ) {
return this.each(function(){
var self = this;
var oldVal = self[id];
$(self).data(
'watch_timer',
setInterval(function(){
if (self[id] !== oldVal) {
fn.call(self, id, oldVal, self[id]);
oldVal = self[id];
}
}, 100)
);
});
return self;
};
jQuery.fn.unwatch = function( id ) {
return this.each(function(){
clearInterval( $(this).data('watch_timer') );
});
};
and creating special event
jQuery.fn.valuechange = function(fn) {
return this.bind('valuechange', fn);
};
jQuery.event.special.valuechange = {
setup: function() {
jQuery(this).watch('value', function(){
jQuery.event.handle.call(this, {type:'valuechange'});
});
},
teardown: function() {
jQuery(this).unwatch('value');
}
};
Anyway, if you need it only as event, you script is nice :)
I know this post/question is a little old, but these days I was behind a similar solution and I found this:
$('#selector').bind('DOMNodeInserted', function(e) {
console.log(e.target);
});
Source: http://naspinski.net/post/Monitoring-a-DOM-Element-for-Modification-with-jQuery.aspx
Hope this help someone!
The finished code in the original question worked for me, thank you! I would just like to note that I am using jquery 1.9.1 and $.event.handle seems to have been removed. I changed the following to get it to work.
jQuery.event.handle.call(self, {type:'contentchange'});
to
jQuery.event.dispatch.call(self, {type:'contentchange'});
maybe you could try Mutation Observer
Here are the code:
mainArea = document.querySelector("#main_area");
MutationObserver = window.MutationObserver;
DocumentObserver = new MutationObserver(function() {
//what you want to run
});
DocumentObserverConfig = {attributes: true, childList: true, characterData: true, subtree: true};
DocumentObserver.observe(mainArea, DocumentObserverConfig);

YUI Event Utility problem

I create a button, when clicked, it activates a backup feature.
My problem, backup is launched before I have clicked to this button.
How, do I fix this problem ? Any Idea ?
Here is my code (fragment) :
(button) :
var oSaveCuratedQuery = new YAHOO.widget.Button({
type: "button",
label: "Save Query",
id: "updateCuratedQuery",
name: "updateCuratedQuery",
value: "updateCuratedQueryValue",
container: idReq });
YAHOO.util.Event.addListener("updateCuratedQuery-button", "click", saveCuratedQuery(idReq, contentCurValue));
(backup function) :
function saveCuratedQuery (geneId,curatedText) {
var handleSuccessGeneQueries = function(o){
Dom.get('progress').innerHTML = "Data Saved...";
}
var handleFailureGeneQueries = function(o){
alert("Save failed...")
}
var callbackGeneQueries =
{
success:handleSuccessGeneQueries,
failure: handleFailureGeneQueries
};
var sUrlUpdate = "save.html?";
var postData = 'key=saveCuratedQuery&value=gene_id==' +geneId+ '--cq==' +curatedText;
var request = YAHOO.util.Connect.asyncRequest('POST', sUrlUpdate, callbackGeneQueries, postData);
}
I also try :
oSaveCuratedQuery.on("click",saveCuratedQuery(idReq, contentCurValue));
But same problem !
The backup is done before I click "save" button.
Thank you for help.
The third argument of addListener should be a function to be run when the event happens.
You are passing it the return value of saveCuratedQuery instead.
var callbackSaveCuratedQuery = function (idReq, contentCurValue) {
return function callbackSaveCuratedQuery () {
saveCuratedQuery(idReq, contentCurValue);
};
}(idReq, contentCurValue); // Use an anonymous closure function
// to ensure that these vars
// do not change before the click
// event fires.
YAHOO.util.Event.addListener("updateCuratedQuery-button",
"click",
callbackSaveCuratedQuery
);
See https://developer.mozilla.org/en/A_re-introduction_to_JavaScript#Closures if you need to learn about closures.

Categories

Resources