Possible Duplicate:
Function triggering early
calling a functions value
I need some help.
I cannot, for the life of me, figure this out. I’ve had my head wrapped around it only to no avail.
I’d like to setup two functions.
-
function:
select_date()to interact with the user to select a date from the jQuery Date picker. If the dialog is closed then return as null. -
Then a second function:
test()to check whether or not a date waspicked/selected.
Here’s my dilemma, when the function test() is executed, an alert box pops up and says "undefined" which means, I never get to select a date and it always being "undefined"
I dont see what I am doing wrong here and everything seems logical to me.
<!DOCTYPE html>
<html>
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.21/jquery-ui.js"></script>
<script type="text/javascript">
function select_date() {
var sdate
$('#dd').dialog({
autoOpen: true,
modal: true,
overlay: {
opacity: 0.5,
background: 'black'
},
title: "title",
height: 265,
width: 235,
draggable: false,
resizable: false
});
$('#d1').datepicker({
onSelect: function () {
$("#dd").dialog("close");
}
});
return sdate
}
function test() {
var x = select_date()
alert(x)
}
</script>
<style type="text/css">
#d1 {font-size:64%;}
</style>
</head>
<body>
<div id="dd">
<div id="d1">
</div>
</div>
<a href="javascript:test()">test</a>
</body>
</html>
It’s the way JavaScript works…
select_date()returns immediately because.dialog()and.datepicker()are asynchronous methods.return sdateis called before anything has even happened. The right way to do it would be to use callback methods fromonSelect()The only issue with this is that the callback will not be called if no date is selected and the dialog is closed. You could add an event listener for that on the dialog and make it call
callbackwith anull/undefinedvalue, but that’s up to you.