Search code examples
javascriptconstantsattr

Replace attr value using const


when I try to modify the attr of an input, for example "data-disabled-dates" replacing the content with a const, the result I get is a text with the name of the const, but not the const content, which would be the correct way to get it.

html

<input data-min-date="+1" data-disabled-dates="24/12/2021; 25/12/2021; 30/12/2021; 31/12/2021">

Javascript/Jquery

const dateObj = new Date();
jQuery("input[data-min-date='+1']").attr('data-disabled-dates','dateObj'); 

So the wrong result is:

<input data-min-date="+1" data-disabled-dates="dateObj">

The result i want (today):

<input data-min-date="+1" data-disabled-dates="16/11/2021">

Solution

  • You wrapped the name of the const in quotes so it became a string.

    solution:

    const dateObj = new Date();
    jQuery("input[data-min-date='+1']").attr('data-disabled-dates',dateObj); 
    

    or if you really want date to be formatted like dd/MM/YYYY:

    const now = new Date();
    jQuery("input[data-min-date='+1']").attr(
      'data-disabled-dates', 
      `${now.getDate()}/${now.getMonth()+1}/${now.getFullYear()}`
    );