I have a php date and wish to echo it out in a javascript alert box:-
$day=15;
$month=8;
$year=2012;
$date_display = date("Y-m-d", mktime(0, 0, 0, $month, $day, $year));
echo $date_display; // 2012年08月15日
Then,
<a href="#" onclick="give_date(<?=$date_display;?>)"><?=$day;?></a>
The javascript function:
<script>
function give_date(value){
alert (value);
}
</script>
Interestingly, the alert box give me "1989", which equals to 2012 minus 8 minus 15!! what shall I do!!
3 Answers 3
Now you get: <a href="#" onclick="give_date(2012年08月15日)">15</a>, so it calculates it in browser.
the solution is simple - add quotes:
<a href="#" onclick="give_date('<?=$date_display;?>')"><?=$day;?></a>
Then you get: <a href="#" onclick="give_date('2012-08-15')">15</a>
Comments
You are making the client-side code show an alert with the date of the server when the page was loaded.
If you want to show the user the current time, use this:
HTML:
<a href="#" id="date">Please enable JavaScript.</a>
JavaScript:
<script type="text/javascript">
function show_date() {
alert(new Date());
}
window.onload = function() {
document.getElementById('date').innerHTML = new Date().getDay();
};
document.getElementById('date').onclick = show_date;
</script>
Comments
You can use jQuery if you are up for it
<a href="#" id="<?php echo $date_display; ?>">Click to get date popup</a>
$(function(){
$('a').click(function(){
var dt = $(this).attr('id');
alert(dt);
});
});
4 Comments
2012年08月05日 is not a good candidate to be used as an id. I'd suggest to use data-date="..." insteadid should begin with letter. It's how standard defines requirement to id. You may do whatever you want, but the standard is a standard. And it is a good idea to follow it
dateit shouldn't make much difference, but in general, you're making a mistake here by confusing between the client-side and the server-side. The value of$date_displayis calculated on the server-side whileonclickis called on the client side. As for your problem, try casting toString.'2012年08月15日'string value or math evaluation. And second - "As for your problem, try casting to String" --- to cast to string what? In php it is a string - makes no sense, in js - it's too late, so makes no sense as well<?php echo $date_display; ?>rather than<?=$date_display;?>. And don't usemktime, usetime.