2

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.

1
  • try without json_encode Commented Jul 28, 2017 at 17:52

1 Answer 1

2

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>
Sign up to request clarification or add additional context in comments.

1 Comment

Was about to say the same thing. It is being treated as a string (and one that is missing apostrophes in the right places, which is another issue itself). The alternative, once fixing the missing apostrophe, could also be to simply echo the string itself, as in echo "... allowTimes:[".$list."] ... " without wrapping it with encode_json.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.