is there an alternative to DOMAttrModified that will work in webkit - dom

I need to leverage this DOM event. IE has onpropertychange, which does what I need it to do also. Webkit doesn't seem to support this event, however. Is there an alternative I could use?

Although Chrome does not dispatch DOMAttrModified events, the more lightweighted mutation observers are supported since 2011 and these work for attribute changes, too.
Here is an example for the document body:
var element = document.body, bubbles = false;
var observer = new WebKitMutationObserver(function (mutations) {
mutations.forEach(attrModified);
});
observer.observe(element, { attributes: true, subtree: bubbles });
function attrModified(mutation) {
var name = mutation.attributeName,
newValue = mutation.target.getAttribute(name),
oldValue = mutation.oldValue;
console.log(name, newValue, oldValue);
}
For a simple attribute change, the console.log statement would print:
<body color="black">
<script type="text/html">
document.body.setAttribute("color", "red");
</script>
</body>
Console:
> color red black

If you are happy with merely detecting calls to setAttribute() (as opposed to monitoring all attribute modifications) then you could over-ride that method on all elements with:
Element.prototype._setAttribute = Element.prototype.setAttribute
Element.prototype.setAttribute = function(name, val) {
var e = document.createEvent("MutationEvents");
var prev = this.getAttribute(name);
this._setAttribute(name, val);
e.initMutationEvent("DOMAttrModified", true, true, null, prev, val, name, 2);
this.dispatchEvent(e);
}

I had the same question and was thinking of modifying setAttribute, so seeing what Sean did, I copied that. Worked great, except that it was firing when an attribute was repeatedly set to the same value, so I added a check to my copy to skip firing the event if the value is not being changed. I also added val = String(val), based on the rationale that setAttribute will coerce numbers to strings, so the comparison should anticipate that.
My modified version is:
var emulateDOMAttrModified = {
isSupportedNatively: function () {
var supported = false;
function handler() {
supported = true;
}
document.addEventListener('DOMAttrModified', handler);
var attr = 'emulateDOMAttrModifiedTEST';
document.body.setAttribute(attr, 'foo'); // aka $('body').attr(attr, 'foo');
document.removeEventListener('DOMAttrModified', handler);
document.body.removeAttribute(attr);
return supported;
},
install: function () {
if (!this.isSupportedNatively() &&
!Element.prototype._setAttribute_before_emulateDOMAttrModified) {
Element.prototype._setAttribute_before_emulateDOMAttrModified = Element.prototype.setAttribute
Element.prototype.setAttribute = function(name, val) {
var prev = this.getAttribute(name);
val = String(val); /* since attributes do type coercion to strings,
do type coercion here too; in particular, D3 animations set x and y to a number. */
if (prev !== val) {
this._setAttribute_before_emulateDOMAttrModified(name, val);
var e = document.createEvent('MutationEvents');
e.initMutationEvent('DOMAttrModified', true, true, null, prev, val, name, 2);
this.dispatchEvent(e);
}
};
}
}
};
// Install this when loaded. No other file needs to reference this; it will just make Chrome and Safari
// support the standard same as Firefox does.
emulateDOMAttrModified.install();

Please refer code:
https://github.com/meetselva/attrchange/blob/master/attrchange.js
'DOMAttrModified' + ('propertychange' for IE) are used there like in your case. If it's not suitable for you, the "ugly" solution that can satisfy this demand should be setInterval(function(){}, delay)
Otherwise see Sean Hogan post above.

The solution provided by #Filip is close (and may have worked at the time) but now you need to request delivery of the old attribute value.
Thus, you'll want to change :
observer.observe(element, { attributes: true, subtree: bubbles });
to this:
observer.observe(element, { attributes: true, attributeOldvalue:true, subtree: bubbles });
Otherwise, you won't see the oldValues (you'll get null instead.) This was tested in Chrome 34.0.1847.131 (Official Build 265687) m.

Related

How can we validate just the mandatory fields in a form in SAP UI5?

I am trying to create a form which has some mandatory fields that requires validation on form submission.
Could anyone suggest me the best possible way to do that in SAP UI5? The mandatory fields are in greater number, thus i don't want to check all fields separately by their ID.
You can do this in two scenarios. While entering a value, or when submitting the form as in your question.
CheckRequired: function(oEvent) {
var aInputs = [this.getView().byId(oEvent.getSource().getId())];
var sError = false;
jQuery.each(aInputs, function(i, input) {
if (!input.getValue() || input.getValue().length < 1) {
input.setValueState("Error");
input.focus();
sError = true;
} else {
input.setValueState("None");
}
});
return sError;
},
This function is to be used with the onLiveChange property. It checks if the control is filled with at least one character.
If you would like to check everything when you press submit. you could use a function like this with your form:
_onSubmitCheck: function() {
var oForm = this.getView().byId("form").getContent();
var sError = false;
oForm.forEach(function(Field) {
if (typeof Field.getValue === "function") {
if (!Field.getValue() || Field.getValue().length < 1) {
Field.setValueState("Error");
sError = true;
}
else {
Field.setValueState("None");
}
}
});
return sError;
},
It will loop over your form controls to check if the getValue() method exists as part of the control. If that returns yes, it wil check if it has a value of at least 1 character.
There are kind of two ways.
add
"sap.ui5": {
...
"handleValidation": true,
to your manifest.json and type & constraints to your inputs
<Input type="Text" value="{path: 'NoFioriValidationsInDefault', type: 'sap.ui.model.type.String', constraints: { minLength:2 }}" valueLiveUpdate="true" enabled="{= ${editView>/nfvid/enabled} && ${editView>/creating}}" visible="true" width="auto" valueHelpOnly="false" maxLength="0" id="inp_cond_nfvid" required="{editView>/nfvid/required}"/>
This gives just visual feedback to the user, if you need the status in your controller you can either iterate over all the inputs and check them by hand, or use https://github.com/qualiture/ui5-validator
Just by calling
var validator = new Validator();
validator.validate(this.byId("form1"));
if (!validator.isValid()){
//do something additional to drawing red borders? message box?
return;
}
in your controller, the view will mark missing required inputs with the ValueState.ERROR (red borders) and tell you if all inputs inside the supplied control are valid.
I am doing it the old-school way. The input fields do get the required=true property and then I loop over all controls found with this property:
// store view ID to compare with control IDs later
var viewId = this.getView().getId();
jQuery('input[required=required]').each(function () {
// control has wrapper with no id, therefore we need to remove the "-inner" end
var oControl = sap.ui.getCore().byId(this.id.replace(/-inner/g,''));
// CAUTION: as OpenUI5 keeps all loaded views in DOM, ensure that the controls found belong to the current view
if (oControl.getId().startsWith(viewId) && (oControl instanceof sap.m.Input || oControl instanceof sap.m.DatePicker)) {
var val = oControl.getValue();
if (!val) {
oControl.setValueState(sap.ui.core.ValueState.Error);
oControl.openValueStateMessage();
bError = true;
return false;
} else {
oControl.setValueState(sap.ui.core.ValueState.None);
oControl.closeValueStateMessage();
}
}
});
HTH,
Anton

Mootools stop form submit method

I don't want to use an <input type=submit /> button to submit a form and I am instead using an <a> element. This is due to styling requirements. So I have this code:
myButton.addEvent('click', function() {
document.id('myForm').submit();
});
However, I have also written a class that improves and implements the placeholder attribute on inputs and textareas:
var FDPlaceholderText = new Class({
Implements: Events,
initialize: function() {
var _self = this;
var forms = document.getElements('form');
forms.each(function(form) { // All forms
var performInit = false;
var i = 0;
var ph = [];
form.getElements('input, textarea').each(function(el) { // Get form inputs and textareas
if (el.getProperty('placeholder') != null) { // Check for placeholder attribute
performInit = true;
ph[i] = _self.initPlaceholder(el); // Assign the placeholder replacement to the elements
}
i ++;
});
if (performInit) {
_self.clearOnSubmit(form, ph);
}
});
},
clearOnSubmit: function(form, ph) {
form.addEvent('submit', function(e) {
ph.each(function(el) {
if (el.value == el.defaultValue) {
el.value = '';
}
});
});
},
initPlaceholder: function(el) {
el.defaultValue = el.getProperty('placeholder');
el.value = el.getProperty('placeholder');
el.addEvents({
'focus': function() {
if (el.value == el.defaultValue) el.value = '';
},
'blur': function() {
if(el.value.clean() == ''){
el.value = el.defaultValue;
}
}
});
return el;
}
});
window.addEvent('domready', function() {
new FDPlaceholderText();
});
The above class works great if a form is submitted using an actual <input type=submit /> button: it listens for a submit and clears the inputs values if they are still the default ones therefore validating that they are essentially empty.
However, it seems that because I am submitting one of my forms by listening to a click event on an <a> tag the form.addEvent('submit', function(e) { isn't getting fired.
Any help is appreciated.
well you can change the click handler to fireEvent() instead of call the .submit() directly:
myButton.addEvent('click', function() {
document.id('myForm').fireEvent('submit');
});
keep in mind a couple of things (or more).
placeholder values to elements that lack placeholder= attribute is pointless
if you detect placeholder support, do so once and not on every element, it won't change suddenly midway through the loop. you can go something like var supportsPlaceholder = !!('placeholder' in document.createElement('input')); - remember, there is no need to do anything if the browser supports it and currently, near enough 60% do.
you can otherwise do !supportsPlaceholder && el.get('placeholder') && self.initPlaceholder(el); - which avoids checking attributes when no need
when the form is being submitted you really need to clear placeholder= values in older browser or validation for 'required' etc will fail. if validation still fails, you have to reinstate the placeholder, so you need a more flexible event pattern
avoid using direct references to object properties like el.value - use the accessors like el.get('value') instead (for 1.12 it's getProperty)
for more complex examples of how to deal with this in mootools, see my repo here: https://github.com/DimitarChristoff/mooPlaceholder
This is because the submit() method is not from MooTools but a native one.
Maybe you can use a <button type="submit"> for your styling requirements instead.

Handle selected event in autocomplete textbox using bootstrap Typeahead?

I want to run JavaScript function just after user select a value using autocomplete textbox bootstrap Typeahead.
I'm searching for something like selected event.
$('.typeahead').on('typeahead:selected', function(evt, item) {
// do what you want with the item here
})
$('.typeahead').typeahead({
updater: function(item) {
// do what you want with the item here
return item;
}
})
For an explanation of the way typeahead works for what you want to do here, taking the following code example:
HTML input field:
<input type="text" id="my-input-field" value="" />
JavaScript code block:
$('#my-input-field').typeahead({
source: function (query, process) {
return $.get('json-page.json', { query: query }, function (data) {
return process(data.options);
});
},
updater: function(item) {
myOwnFunction(item);
var $fld = $('#my-input-field');
return item;
}
})
Explanation:
Your input field is set as a typeahead field with the first line: $('#my-input-field').typeahead(
When text is entered, it fires the source: option to fetch the JSON list and display it to the user.
If a user clicks an item (or selects it with the cursor keys and enter), it then runs the updater: option. Note that it hasn't yet updated the text field with the selected value.
You can grab the selected item using the item variable and do what you want with it, e.g. myOwnFunction(item).
I've included an example of creating a reference to the input field itself $fld, in case you want to do something with it. Note that you can't reference the field using $(this).
You must then include the line return item; within the updater: option so the input field is actually updated with the item variable.
first time i've posted an answer on here (plenty of times I've found an answer here though), so here's my contribution, hope it helps. You should be able to detect a change - try this:
function bob(result) {
alert('hi bob, you typed: '+ result);
}
$('#myTypeAhead').change(function(){
var result = $(this).val()
//call your function here
bob(result);
});
According to their documentation, the proper way of handling selected event is by using this event handler:
$('#selector').on('typeahead:select', function(evt, item) {
console.log(evt)
console.log(item)
// Your Code Here
})
What worked for me is below:
$('#someinput').typeahead({
source: ['test1', 'test2'],
afterSelect: function (item) {
// do what is needed with item
//and then, for example ,focus on some other control
$("#someelementID").focus();
}
});
I created an extension that includes that feature.
https://github.com/tcrosen/twitter-bootstrap-typeahead
source: function (query, process) {
return $.get(
url,
{ query: query },
function (data) {
limit: 10,
data = $.parseJSON(data);
return process(data);
}
);
},
afterSelect: function(item) {
$("#divId").val(item.id);
$("#divId").val(item.name);
}
Fully working example with some tricks. Assuming you are searching for trademarks and you want to get the selected trademark Id.
In your view MVC,
#Html.TextBoxFor(model => model.TrademarkName, new { id = "txtTrademarkName", #class = "form-control",
autocomplete = "off", dataprovide = "typeahead" })
#Html.HiddenFor(model => model.TrademarkId, new { id = "hdnTrademarkId" })
Html
<input type="text" id="txtTrademarkName" autocomplete="off" dataprovide="typeahead" class="form-control" value="" maxlength="100" />
<input type="hidden" id="hdnTrademarkId" />
In your JQuery,
$(document).ready(function () {
var trademarksHashMap = {};
var lastTrademarkNameChosen = "";
$("#txtTrademarkName").typeahead({
source: function (queryValue, process) {
// Although you receive queryValue,
// but the value is not accurate in case of cutting (Ctrl + X) the text from the text box.
// So, get the value from the input itself.
queryValue = $("#txtTrademarkName").val();
queryValue = queryValue.trim();// Trim to ignore spaces.
// If no text is entered, set the hidden value of TrademarkId to null and return.
if (queryValue.length === 0) {
$("#hdnTrademarkId").val(null);
return 0;
}
// If the entered text is the last chosen text, no need to search again.
if (lastTrademarkNameChosen === queryValue) {
return 0;
}
// Set the trademarkId to null as the entered text, doesn't match anything.
$("#hdnTrademarkId").val(null);
var url = "/areaname/controllername/SearchTrademarks";
var params = { trademarkName: queryValue };
// Your get method should return a limited set (for example: 10 records) that starts with {{queryValue}}.
// Return a list (of length 10) of object {id, text}.
return $.get(url, params, function (data) {
// Keeps the current displayed items in popup.
var trademarks = [];
// Loop through and push to the array.
$.each(data, function (i, item) {
var itemToDisplay = item.text;
trademarksHashMap[itemToDisplay] = item;
trademarks.push(itemToDisplay);
});
// Process the details and the popup will be shown with the limited set of data returned.
process(trademarks);
});
},
updater: function (itemToDisplay) {
// The user selectes a value using the mouse, now get the trademark id by the selected text.
var selectedTrademarkId = parseInt(trademarksHashMap[itemToDisplay].value);
$("#hdnTrademarkId").val(selectedTrademarkId);
// Save the last chosen text to prevent searching if the text not changed.
lastTrademarkNameChosen = itemToDisplay;
// return the text to be displayed inside the textbox.
return itemToDisplay;
}
});
});

How to access old and new values before submitting with jeditable

I have a field being updated by jeditable. I want to output a warning message before submitting updates if the value is being reduced (which would result in data being lost), but not if it's being increased.
This seems a good candidate for jeditable's onsubmit function, which I can trigger happily. I can get the new value from $('input', this).val(), but how do I get the original value to which to compare it in this context?
...
Since posting the above explanation / question, I've come up with a solution of sorts. By changing the invokation in jquery.ready from
$('#foo').editable(...);
to
$('#foo').hover(function(){
var old_value = $(this).text();
$(this).editable('ajax.php', {
submitdata {'old_value':old_value}
});
});
I can use settings.submitdata.old_value in the onsubmit method.
But there surely has to be a better way? jeditable must still have the old value tucked away somewhere in order to be able to revert it. So the question becomes how can I access that from the onsubmit function?
Many thanks in advance for any suggestions.
A much easier solution would be to add this line to your submitdata variable
"submitdata": function (value, settings) {
return {
"origValue": this.revert
};
}
Here is my editable (it is using the submitEdit function):
$(function () {
$('.editable').editable(submitEdit, {
indicator: '<img src="content/images/busy.gif">',
tooltip: '#Html.Resource("Strings,edit")',
cancel: '#Html.Resource("Strings,cancel")',
submit: '#Html.Resource("Strings,ok")',
event: 'edit'
});
/* Find and trigger "edit" event on correct Jeditable instance. */
$(".edit_trigger").bind("click", function () {
$(this).parent().prev().trigger("edit");
});
});
In submitEdit origvalue is the original value before the edit
function submitEdit(value, settings) {
var edits = new Object();
var origvalue = this.revert;
var textbox = this;
var result = value;
// sb experiment
var form = $(this).parents('form:first');
// end experiment
edits["field"] = form.find('input[name="field"]').val();
edits["value"] = value;
var returned = $.ajax({
url: '#Url.Action("AjaxUpdate")',
type: "POST",
data: edits,
dataType: "json",
complete: function (xhr, textStatus) {
// sever returned error?
// ajax failed?
if (textStatus != "success") {
$(textbox).html(origvalue);
alert('Request failed');
return;
}
var obj = jQuery.parseJSON(xhr.responseText);
if (obj != null && obj.responseText != null) {
alert(obj.responseText);
$(textbox).html(origvalue);
}
}
});
return (result);
}

Drag from Tree to div

I am trying to implement a drag and drop senario from an extJs TreePanel into a div in the body of the page. I have been following an example by Saki here.
So far I have the below code:
var contentAreas = new Array();
var tree = new Ext.tree.TreePanel({
title : 'Widgets',
useArrows: true,
autoScroll: true,
animate: true,
enableDrag: true,
border: false,
layout:'fit',
ddGroup:'t2div',
loader:new Ext.tree.TreeLoader(),
root:new Ext.tree.AsyncTreeNode({
expanded:true,
leaf:false,
text:'Tree Root',
children:children
}),
listeners:{
startdrag:function() {
$('.content-area').css("outline", "5px solid #FFE767");
},
enddrag:function() {
$('.content-area').css("outline", "0");
}
}
});
var areaDivs = Ext.select('.content-area', true);
Ext.each(areaDivs, function(el) {
var dd = new Ext.dd.DropTarget(el, {
ddGroup:'t2div',
notifyDrop:function(ddt, e, node) {
alert('Drop');
return true;
}
});
contentAreas[contentAreas.length] = dd;
});
The drag begins and the div highlights but when I get over the div it does not show as a valid drop target and the drop fails.
This is my first foray into extJS. I'm JQuery through and through and I am struggling at the moment.
Any help would be appreciated.
Ian
Edit
Furthermore if I create a panel with a drop target in it, this works fine. What is the difference between creating an element and selecting an existing element from the dom. This is obviously where I am going wrong but I'm none the wiser. I have to be able to select existing dom elements and make them into drop targets so the code below is not an option.
Here is the drop target that works
var target = new Ext.Panel({
renderTo: document.body
,layout:'fit'
,id:'target'
,bodyStyle:'font-size:13px'
,title:'Drop Target'
,html:'<div class="drop-target" '
+'style="border:1px silver solid;margin:20px;padding:8px;height:140px">'
+'Drop a node here. I\'m the DropTarget.</div>'
// setup drop target after we're rendered
,afterRender:function() {
Ext.Panel.prototype.afterRender.apply(this, arguments);
this.dropTarget = this.body.child('div.drop-target');
var dd = new Ext.dd.DropTarget(this.dropTarget, {
// must be same as for tree
ddGroup:'t2div'
// what to do when user drops a node here
,notifyDrop:function(dd, e, node) {
alert('drop');
return true;
} // eo function notifyDrop
});
}
});
See if adding true as the second param here makes any difference:
var areaDivs = Ext.select('.content-area', true);
As a cosmetic note, the param name e conventionally indicates an event object (as in the second arg of notifyDrop). For an element, el is more typical. Doesn't matter functionally, but looks weird to someone used to Ext code to see e passed into the DropTarget constructor.
If you are having problem duplicating a working example such as that, copy the entire thing, then modify it to your needs line-by-line - you can't go wrong.
As i know you can't set DropZone to any Ext element, just to Ext component. So this might be you problem. Try to use DropTarget instead of DropZone.