Home > other >  Run action if contains part of an attr value
Run action if contains part of an attr value

Time:02-16

I have a input with this

attr('data-disabled-dates','12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022')

And a const which results in tomorrow dynamically, so for this case the result is "16/02/2022"

Now i want to run action if it matches that tomorrow's date is within the attr data-disabled-dates.

So i tried this

if (jQuery(input).attr('data-disabled-dates') == '16/02/2022')
        { console.log('work') } else {
    console.log ('not') }

But it only gives me true if the whole sequence is exactly the same, that is, if I put "12/02/2022; 13/02/2022..." if it will give the result, but I only want it to be true if the value I am putting is inside

CodePudding user response:

You can use String.includes() or String.split('; ') to convert string to array and check if it includes the desired value.

if (jQuery(input).attr('data-disabled-dates').includes('16/02/2022')) { 
  console.log('work') 
} else {
  console.log('not') 
}

Working example in vanilla JS

const div = document.querySelector('#data');

const dates = div.getAttribute('data-disabled-dates');

if (dates.includes('16/02/2022')) {
  console.log('work')
} else {
  console.log('not')
}


// or
if (dates.split('; ').includes('16/02/2022')) {
  console.log('work')
} else {
  console.log('not')
}
<div id="data" data-disabled-dates="12/02/2022; 13/02/2022; 14/02/2022; 15/02/2022; 10/03/2022; 11/03/2022; 16/02/2022" />

btw https://youmightnotneedjquery.com/

CodePudding user response:

== performs exact string matches, not substring matches.

You can use .split() to split the attribute value into an array, then use .includes() to test if the array contains the date.

if (jQuery(input).data('disabled-dates').split('; ').includes('16/02/2022')) {
    console.log("work");
} else {
    console.log("not");
}

CodePudding user response:

You can use indexOf to be greater than 0. IndexOf if you need to support IE.

var dataAttrValue = jQuery(input).attr('data-disabled-dates');
var date = '16/02/2022';
if (typeof dataAttrValue !== 'undefined' && dataAttrValue.indexOf(date)) > 0) { console.log('work');
} else {
console.log ('not');
}

OR

jQuery(input).is(“[data-disabled-dates*='16/02/2022']”);

But I suggest using JQuery Data to store and retrieve values from elements.

  • Related