Link to home
Start Free TrialLog in
Avatar of Member_2_1242703
Member_2_1242703

asked on

Using jQuery to set a DIV attribute on page load

I have the following DIV

<div class="input-group input-append date" data-date-format="mm-dd-yyyy" id="dp2" data-date="01/25/2017">

Open in new window


I want to set the value of "data-date" to the current date when the page loads. How would I do that?
ASKER CERTIFIED SOLUTION
Avatar of Guy Hengel [angelIII / a3]
Guy Hengel [angelIII / a3]
Flag of Luxembourg image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Member_2_1242703
Member_2_1242703

ASKER

You have 2 id listed...I changed to the following:

    <script type="text/javascript">
 
  $(function() {
    var d = new Date();
    // in the format you want  
    var strDate = (d.getMonth()+1) + d.getDate() + "/" +  "/" + d.getFullYear() ;

    $( "#dp2" ).attr('data-date', strDate); 
 
  });
</script>

Open in new window


and got  JavaScript runtime error: '$' is undefined
you need to include the jquery libraries, which i assumed already done as you requested this to be done with jquery...
I do. I have other functions on the same page working fine.
Your date string is wrong (line 6)
var strDate = (d.getMonth()+1) + d.getDate() + "/" +  "/" + d.getFullYear() ;

Open in new window

- I think you meant this
 var strDate = (d.getMonth()+1) + "/" + d.getDate() + "/"  + d.getFullYear() ;

Open in new window

Make sure your script is included AFTER the jQuery libraries

This works with the above amendment (http://www.marcorpsa.com/ee/t2060.html)
Kind of strange here, I have my libraries referenced in a master page which works good, except for this (and others I presume?) Anyhow, I added the reference again to this page itself and the following works great.

<script type="text/javascript">
    $(document).ready(function () {
        $("#dp3").attr("data-date", Date());
    });
</script>
How does this
var strDate = (d.getMonth()+1) + d.getDate() + "/" +  "/" + d.getFullYear() ;

Open in new window

Produce this?
mm/dd/yyyy

There is a double "/" + "/" in the string?