Identify which control my application is using - javascript

I got a method into my masterpage which populates a value to every label I pass:
function FillLabel(field, text)
{
$(field).html(text);
}
I'll need to make it adaptable to the situation that my field receive an html input and to put the text inside this input I need to use $(field).html(text);
I need to build an if to identify the type of the field and I have no idea how to do that. How can I do this?

You don't give enough details ! According to your code snippet, you seem to talk about JavaScript based on jQuery.
You can test the type of an element with the is() method and selectors :
var element=$(field);
if(element.is(":input")) element.val(text);
else element.html(text);

You can check the tag name:
var tag = $(field).attr('tagName');
edit — #Cédric Belin correctly suggests ".is()":
var isInput = $(field).is(':input');
Much more jQuery-like.
Or check to see if there's a "value" property:
if ('value' in $(field)[0]) { ... }
So, overall:
function FillLabel(field, text) {
var $field = $(field);
if ('value' in $field[0])
$field.val(text);
else
$field.html(text);
}
You might consider using ".text()" instead of ".html()" but I don't know what your application needs are. You also might consider writing this as a jQuery plugin.

Related

Custom Unobtrusive Validation Method Not Firing as Per Documentation

I've been attempting to implement a ASP.NET MVC custom validation method. Tutorials I've used such as codeproject explain that you add data-val-customname to the element. Then jQuery.validate.unobtrusive.js then uses the third segment of the attribute
data-val-<customname>
as the name of the rule, as shown below.
$.validator.addMethod('customname', function(value, element, param) {
//... return true or false
});
However I just can't get the customname method to fire. By playing around I have been able to get the below code to work, but according to all the sources I've read Unobtrusive validation should not work like this.
$.validator.addMethod('data-val-customname', function(value, element, param) {
//... return true or false
});
I've posted an example of both methods
jsfiddle example
Any help would be much appreciated
I've updated my question hopefully to make clearer.
I have finally found got there in the end, but still feels like too much hard work and therefore I've probably got something wrong. Initial I was scuppered by a bug in Chrome Canary 62 which refused to allow the adding of a custom method.
My next issue was having to load jQuery, jQuery.validate and jQuery.validate.unobtrusive in the markup and then isolate javascript implementation in a ES6 class. I didn't want to add my adaptors before $().ready() because of my class structure and loading of the app file independent of jQuery. So I had to force $.validator.unobtrusive.parse(document);.
Despite this I was still having issues and finally debugged the source code and found that an existing validator information that is attached to the form was not merging with the updated parsed rules, and essentially ignoring any new adaptors added.
My final work around and admit feels like I've done too much, was to destroy the initial validation information before my forced re-parse.
Here is the working jsfiddle demo
Here is some simplified code
onJQueryReady() {
let formValidator = $.data(document.querySelector('form'), "validator" );
formValidator.destroy();
$.validator.unobtrusive.adapters.add("telephone", [], function (options) {
options.rules['telephone'] = {};
options.messages['telephone'] = options.message;
});
$.validator.unobtrusive.parse(document);
$.validator.addMethod("telephone", this.handleValidateTelephoneNumber);
}

How to remove the "name" param in for fields in ExtJS 4

I am integrating a payment provider into a ExtJS websites.
Basically, a form needs to be created and the form fields is send to the payment provider using Ajax.
The problem is that the payment provider does not allow that the form fields has a "name" param assigned to the "" tag. They do a manual check of the implementation and makes sure it is not there.
I assume it is a counter-mesasure for when the visitor has Ajax dissabled and the form gets submitted to my server instead, revealing the credit card. I know it does not make any sense with ExtJS, as it would not work without Javascript turned on, but non-the-less, that is the rule from the payment provider.
So, how can I force ExtJS to not put a "name" param in the form field? I have tried putting "name: ''" into the fields, but that gets ignored.
Do I use the template-system in ExtJS to solve this?
So Eric is perfectly right that it can be done much easier then modifying the whole template but non the less I would use a plugin for such a special case. I made a quick one:
Ext.define('Ext.form.field.plugin.NoNameAttribute', {
extend: 'Ext.AbstractPlugin',
alias: 'plugin.nonameattribute',
init: function(cmp) {
Ext.Function.interceptAfterCust(cmp, "getSubTplData", function(data){
delete data['name'];
return data;
});
}
});
Note the used method interceptAfterCust is a custom one of mine that modify the existing one by handing the result of the original to the intercepting one as argument. It is also using the given original object (which can be threaten as a scope) as scope for the original method. The easiest would be to add these method to Ext.Function
Ext.Function.interceptAfterCust = function(object, methodName, fn, scope) {
var method = object[methodName] || Ext.emptyFn;
return (object[methodName] = function() {
return fn.call(scope || this, method.apply(object, arguments));
});
}
Here is a working JSFiddle where the first field will not have a name attribute on the dom even if it exist in the component.
There's a surprisingly simple solution to this. I tested it with Ext.form.field.Text and Ext.form.field.ComboBox and it works well, but I don't know if it works for all form fields or if there are any negative side-effects. Use with caution.
Ext.define('Override.form.field.Base', {
override: 'Ext.form.field.Base',
getSubTplData: function(){
var data = this.callParent(arguments);
delete data.name;
return data;
}
});
Basically, it removes the auto-generated name from the render data before passing it along. The best part is that no private methods are involved so this should be a stable solution.
I prefer this in the field config options:
submitValue: false
Available since ExtJS 3.4

Querying the DOM in Windows 8 Apps from within a method

I'm struggling with this even after reading the MSDN documentation and the following online guides:
Codefoster
Stephen Walter
I think my problem is easy to fix and that I just am thinking about something in the wrong way. Basically I am querying my web service and on success running the following method. I am then trying to bind the result to my listview. For now I am using a hardcoded value publicMembers.itemlistwhich has been declared at the top of the document just to make sure I can actually bind to the list before doing it with my query results. Ignore line 2 for now.
Success Method:
_lookUpSuccess: function xhrSucceed(Result) {
var response = JSON.parse(Result.responseText);
listView = document.querySelector("#termTest");
ui.setOptions(listView, {
itemDataSource: publicMembers.itemList,
itemTemplate: document.querySelector(".itemtemplate"),
})
},
Now, instead of using document.querySelector, I have also tried with WinJS.Utilities.id and WinJS.Utilities.query, neither of which worked either. This doesn't break my code and introduce an error but it doesn't bind to the listview either so I think I have an issue in querying the right DOM element. However exactly the same code does work if I add it to the top of the script, it is only when I place it in this method that it stops working.
EDIT: Also to clarify, when I debug publicMembers.itemList is storing the values I expect them to be.
Please point out if I have explained things poorly and I will try and improve my question.
Thanks.
I haven't used WinJS.UI.setOptions, but rather this other way of setting the data source. Can you see if it works?
_lookUpSuccess: function xhrSucceed(result) {
var response = JSON.parse(result.responseText);
listView = document.querySelector("#termTest");
listView.winControl.itemDataSource = publicMembers.itemList;
},
This would assume you're defining the itemTemplate as part of the data-win-options attribute of your ListView's HTML element. You could also probably just do listView.winControl.itemTemplate = document.querySelector(".itemtemplate") if you prefer to set it programmatically.

jQuery validation fails when using .element(element) within custom method

I have a custom rule that should check some dependencies by validating the other inputs this one depends on. When I do stuff like that validation for all other inputs seems to be ignored.
This one is my custom validation rule:
jQuery.validator.addMethod("checkDependencies", function (value, element) {
var valid1 = jQuery('form#add-lottery-form').validate().element('#input-1');
var valid2 = jQuery('form#add-lottery-form').validate().element('#input-2');
if (valid1 && valid2) {
return true;
} else {
return false;
}
}, 'dependencie error');
I have created a jsfiddle to show my problem:
http://jsfiddle.net/AQcrW/
steps to reproduce:
type something in input4 (this input is the one with custom rule "checkDependencies") [line 1 in JavaScript-part]
errors on input1 and input2 are shown due to calls in JS line 2 and line 3
insert correct values to input1 and input2
click submit
!!recognize that input3 was not validated!!
rerun the fiddle
click submit
all fields are validated as expected
Is this my fault or is it a bug in jQuery validation?
After some debugging and overview the plugins code i have a solution for my problem. I extended the validator plugin to be able to call the internal .check(element) function. this function just returns true/false. Its not a perfect solution because it does some stuff twice on form submit but at least it works so far.. so here is the code I added:
no need for the code - read edit!
jQuery.extend(jQuery.validator.prototype, {
check: function (element)
{
return this.check(element);
}
});
and here is the working fidde:
http://jsfiddle.net/HrPRL/
to follow my thoughts and maybe check out upcoming discussion:
https://github.com/jzaefferer/jquery-validation/issues/579
Edit:
As i realized right now my pretty cool jQuery extend doesn't have any effect..
because the .check() method is part of the prototype object you can access it already. So the code above is not needed.
Edit 2:
this is what I ended up with. It's working but I think some stuff could be optimized.
any better ideas to do it?
http://jsfiddle.net/HrPRL/6/
i am done.. thats enough for my intention: http://jsfiddle.net/HrPRL/8/

Prototype: call custom function after validation

I'm using prototype and needs to call my function after succesfull validation.
Part of the code:
var validator = new Validation(this.form);
this will validate the form, but I don't know how to call my function trackForm after the validation is correct and the form is submited.
Any help?
I would need more details to answer, at least will try then.
I assume you're using PrototypeJS - the library. This lib does not support validation by default so you're probably using another library for that.
If you're using Dexagogo's validation (http://tetlaw.id.au/view/javascript/really-easy-field-validation) you will need to use onFormValidate callback.
I never used it, but presume you basically setup Validation like normally, with addition of that extra attribute. Like this:
var validator = new Validator(this.form, {onFormValidate: trackForm});
var trackForm = function (validationPassed, form) {
if (validationPassed) {
form.reset();
}
}
Ofc you don't need to create trackForm, but written as you mentioned about it.
Hope this somewhat helps.
I appreciate that the original question didn't mention the platform, but I found this question after Googling extensively for a solution on the Magento platform.
For those using Prototype through Magento and Magento's VarienForm, there's a simple way to do with without using any other validation libraries.
The validator is attached to the form when its initialised, and the onFormValidate method is an option on the validator.
You can access is as below:
this.form.validator.options.onFormValidate = function(validationPassed, form) {};
See the below example which I have tested for my own means and found it works exactly as expected:
var contactForm = new VarienForm('contactForm', true);
contactForm.validator.options.onFormValidate = function(validationPassed, form) {
if(validationPassed){
alert("Validation Passed");
}
}

Categories

Resources