Reputation: 14145
inside js script I'm trying to recognize if data-val-required exist on certain element.
var attrExist = $('#myElem').find('[data-val-required]');
if (attrExist.length > 0){
// todo
}
but this doesn't work, cause I'm getting always inside console attrExist as Object[].
How can test if data-val-required attr exist?
update: rendered html looks like
<select id="myElem" class="multiselect form-control" name="someName"
multiple="multiple" data-val-required="This field is required."
data-val="true" style="display: none;">
Upvotes: 0
Views: 2639
Reputation: 18113
The problem in your code is that the find()
function looks inside #myElem
if there exists a element with a data-val-required
attribute.
So if you want to check if #myElem
has the attribute data-val-required
use:
var dataAttr = $('#myElem').data('val-required');
//var dataAttr = $('#myElem').attr('data-val-required'); // alternative
if (typeof dataAttr !== typeof undefined && dataAttr !== false) {
// attribute is set
}
As alternative, you can look if there is any element that has both the id and attribute (by using, id and attribute selector). This solution makes most sense when using classes.
if( $('#myElem[data-val-required]').length > 0 ) {
// element with that attribute exists
}
Upvotes: 1
Reputation: 25527
You can do,
if ($('#myElem[data-val-required]').length > 0)
Your code will check for the child elements which have data-val-required
attribute
Upvotes: 1