Reputation: 2674
I simply want to get the current value of a field's attribute.
This field has a default value like:
<input validation="defaultValue" />
When i want to get the validation attribute, i don't know if it has been updated before or if this is still the default value.
So the property get with prop()
return undefined
when the property is not set (not yet updated), and the attr()
method return always the default value (that's not true actually for maintainability but that will be in the future).
Is there a method that check:
if property is set => return property else return attribute
Thanks
Upvotes: 1
Views: 963
Reputation: 348972
This snippet will do:
var input = $("input");
var method = typeof input.prop("validation") != "undefined" ? "prop" : "attr";
input[method]("validation");
//Shortened to:
var input = $("input");
input[typeof input.prop("validation")!="undefined"?"prop":"attr"]("validation");
Explanation:
typeof ... "undefined"
, the "prop"
string returns. Otherwise, the "attr"
string returns.input
object, either input["prop"]
(=input.prop
) or input["attr"]
(=input.attr
)."validation"
as an argument, resulting in:I recommend to use data-validation
instead of validation
, to be HTML5-compliant.
(function($){
/* Defines the curProp method - Getting the current property
* When the property exists, the prop method is used. Otherwise: attr */
$.fn.curProp = function(name){
return this[typeof this.prop(name) == "undefined" ? "attr" : "prop"](name);
}
})(jQuery);
Upvotes: 4