问题
I found similar questions on here but most of the solutions don't work for me. I have a form with a datepicker and I want to pass the selected date to my php file but it doesn't seem to work.
My html is something like this:
<form name="myForm" action="createevent.php" onsubmit="return validateForm()" method="get">
<p>Date<input type="text" id="mydate" /></p>
<input type="submit" name="submit" value="Submit" />
</form>
Javascript:
$(function() {
$.datepicker.setDefaults($.extend($.datepicker.regional[""]));
$("#mydate").datepicker({
onSelect: function(dateText, inst) {
var dateAsString = dateText;
alert (dateAsString); //this prints out the right value.
alert (mydate.value); //this value is the same as dateText
}
});
createevent.php
function CreateEvent()
{
if(isset($_GET['submit']))
{
$mydate=$_GET['mydate'];
echo $mydate;
}
}
When I alert (mydate.value), it gives the correct value. But when I echo $mydate in my php file, it doesn't show anything. Any help is appreciated!
Update:
Thank you guys! I made a silly mistake. Adding "name" attribute works. I have a follow up question. I have a timepicker as well and it returns something like 01:21. My date returns something like 01/01/2013. Is there a way to combine these two and make it a datetime type so I can add to my database? Thank you so much!
回答1:
Since it seems you're doing nothing with the date after the onSelect has fired, the only thing wrong I see is that your input is lacking the name attribute, and it won't be visible in the $_GET superglobal
Change your input to something like:
<input type="text" id="mydate" name="mydate"/>
And it should work.
If you plan to store your date and time in a MySQL database, you could do something like this. First in your form:
<form name="myForm" action="createevent.php" onsubmit="return validateForm()" method="get">
<p>Date<input type="text" id="mydate" name="mydate"/></p>
<p>Time<input type="text" id="mytime" name="mytime"/></p>
<input type="hidden" id="mydatetime" name="mydatetime"/>
<input type="submit" name="submit" value="Submit" />
</form>
Then, in your validateForm() function, I would add something like this:
var date = $('#mydate').val(),
time = $('#mytime').val();
var datetime = [date.replace('/','-'),time].join(' '); // 01-01-2013 01:21
$('#mydatetime').val(datetime);
回答2:
I didn't tried but I'm wondering maybe it's just your control got "name" missing, try change it as following:
<input type="text" id="mydate" name="mydate"/>
回答3:
Made change in input box
<input type="text" id="mydate" />
TO :
<input type="text" id="mydate" name="mydate"/>
When you will submit form it will submit name value of textbox mydate and you can get it by $_GET["mydate"]
来源:https://stackoverflow.com/questions/14556659/pass-selected-date-values-from-datepicker-to-php