检查是否存在data-val-required

时间:2021-10-15 16:10:34

inside js script I'm trying to recognize if data-val-required exist on certain element.

在js脚本里面我试图识别某些元素上是否存在data-val-required。

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[].

但这不起作用,因为我总是在控制台attrExist中作为Object []。

How can test if data-val-required attr exist?

如何测试data-val-required attr是否存在?

update: rendered html looks like

更新:渲染的html看起来像

<select id="myElem" class="multiselect form-control" name="someName"
         multiple="multiple" data-val-required="This field is required." 
         data-val="true" style="display: none;">

2 个解决方案

#1


1  

The problem in your code is that the find() function looks inside #myElem if there exists a element with a data-val-required attribute.

您的代码中的问题是,如果存在具有data-val-required属性的元素,则find()函数会在#myElem内部查找。

So if you want to check if #myElem has the attribute data-val-required use:

因此,如果要检查#myElem是否具有data-val-required属性,请使用:

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.

或者,您可以查看是否有任何元素同时具有id和属性(通过using,id和attribute selector)。使用类时,此解决方案最有意义。

if( $('#myElem[data-val-required]').length > 0 ) {
    // element with that attribute exists
}

#2


1  

You can do,

你可以做,

if ($('#myElem[data-val-required]').length > 0)

Your code will check for the child elements which have data-val-required attribute

您的代码将检查具有data-val-required属性的子元素

#1


1  

The problem in your code is that the find() function looks inside #myElem if there exists a element with a data-val-required attribute.

您的代码中的问题是,如果存在具有data-val-required属性的元素,则find()函数会在#myElem内部查找。

So if you want to check if #myElem has the attribute data-val-required use:

因此,如果要检查#myElem是否具有data-val-required属性,请使用:

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.

或者,您可以查看是否有任何元素同时具有id和属性(通过using,id和attribute selector)。使用类时,此解决方案最有意义。

if( $('#myElem[data-val-required]').length > 0 ) {
    // element with that attribute exists
}

#2


1  

You can do,

你可以做,

if ($('#myElem[data-val-required]').length > 0)

Your code will check for the child elements which have data-val-required attribute

您的代码将检查具有data-val-required属性的子元素