Richard
Richard

Reputation: 31

PHP variable value pass to DatePicker Javascript

I am just a hobby player, and I have a little trouble with the DateTimePicker available time listing. I am looking for help to understand why is the codes are not working. I am not building any websites or like that, I am just practising.

Basic:

<script>
$('#datetimepicker4').datetimepicker({ 
minDate:new Date(), 
allowTimes:['10:30','11:30','12:30'] });
</script>

Those 3 allowed times listed perfectly.

My question is just a principal: Why is it not working like this?

Only example:

$time1 = "10:30";
$time2 = "11:30";
$time3 = "12:30";

$list = "'" . $time2 . "'," . $time3 . "'";

echo "<script>\n";
echo "$('#datetimepicker4').datetimepicker({ minDate:new Date(), allowTimes:[".json_encode($list)."] });";
echo "\n</script>";

If I am print out the "$list" php variable, it will be showing:'11:30','12:30'. But in the js showing only 1 allowed time rather than 2. Actually it can be 10 different times, still showing only 1.

I can't see the difference between the two ways of listing.

If you can give me an answer I will appreciated.

Thank you.

Upvotes: 2

Views: 133

Answers (1)

Samuel Cook
Samuel Cook

Reputation: 16828

The reason that it's only showing one time is that you're only printing one parameter to allowedTimes.

[".json_encode($list)."] where everything is being wrapped in double quotes. Your output is ["'11:30',12:30'"]. So you need to remove the double quotes in order to have multiple values.

Furthermore, this isn't the most efficient way to do this. If you know that you're print an array, why not set up the times that way?

Example:

<?php
$allowTimes = array(
    '10:30',
    '11:30',
    '12:30'
);
?>

<script>
$('#datetimepicker4').datetimepicker({ minDate:new Date(), allowTimes:<?php echo json_encode($allowTimes) ?> });
</script>

Upvotes: 2

Related Questions