Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

shweta11's avatar

Update date value on document.ready()

I want to change value for

Code in my js file $(document).ready(function() { // Check if #donationtype1 has a value

var donationType1Value = $('#donationtype1').val();
var startdate1 = $('#start-date1').val();
// If #donationtype1 has a value, set the corresponding option as selected in #donationtype
if (donationType1Value) {        
    // console.log(startdate1);
    $('#donationtype').val(donationType1Value).change();
    var formattedStartDate = moment(startdate1, 'YYYY-MM-DD').format('MM/DD/YYYY');
  
  // Set the formatted date as the value of the #start-date input field
  $('#start-date').val(formattedStartDate).change();
}

});

for above code value is set but not displayed in input for start-date

0 likes
6 replies
hupp's avatar

@shweta11

$('#donationtype').val(donationType1Value).trigger('change');

Change this line & Try it. Let know your feedback

shweta11's avatar

@hupp Need solution on "start-date" though it is set on id="start-date" but not displayed in input box

hupp's avatar

@shweta11 Oops! Verify the date format: Ensure that the startdate1 variable holds a valid date in the format 'YYYY-MM-DD'. If the date format is incorrect or contains invalid characters, the moment() function might not parse it correctly.

hupp's avatar

@shweta11 You can also try

$('#start-date').val(formattedStartDate).trigger('change');
aruszala's avatar

@shweta11 try:

// Check if #donationtype1 has a value
$(document).ready(function() {
  var donationType1Value = $('#donationtype1').val();
  var startdate1 = $('#start-date1').val();
  // If #donationtype1 has a value, set the corresponding option as selected in #donationtype
  if (donationType1Value) {        
    // console.log(startdate1);
    $('#donationtype').val(donationType1Value);
    var formattedStartDate = moment(startdate1, 'YYYY-MM-DD').format('MM/DD/YYYY');

    // Set the formatted date as the value of the #start-date input field
    $('#start-date').val(formattedStartDate);
  }
});

The .val() method in jQuery is used to get or set the value of an input element:

$('input').val(); // get the value of the input element
$('input').val('new value'); // set the value of the input element to 'new value'

The .change() method in jQuery is used to bind an event handler to the change event of an input element:

$('input').change(function() {
  // do something when the input element changes
});
Snapey's avatar

why not set the date in blade if you are setting it on page load using data that the backend already has?

Please or to participate in this conversation.