Search code examples
javascriptjqueryif-statementcontainsattr

Run action if contains part of an attr value


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


Solution

  • 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/