user1765862 user1765862 - 1 year ago 136
Javascript Question

checking if data-val-required exist

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?

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;">

Answer Source

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
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download