Jonny Barnes
Jonny Barnes

Reputation: 535

Changing a form input to the current time [jquery]

I have a form with an input that contains the date in the form: 12:00:59 am, 25 December 2010

The most likely time I'd want to change this to is the current time.

Is it possible to have a button or link next to the input field that when clicked jquery would update the time to the current time.

(I'm already using jquery for something else so thought it'd be easier to append a bit more code to my js file than code from scratch)

I can't do this. Here's the html:

<form>
    ...
    <p>Time: <input name="time" id="time" type="text" size="30" value="<?php echo $date; ?>"><a href="" name="time-update">Update to now</a></p>
    ...
</form>

And heres the JS:

$("a[time-update]").click(function(event) {
    var time = Date();
    $("#time").value = time;
    event.preventDefault();
} );

It just reloads the page.

Upvotes: 0

Views: 1789

Answers (2)

Sinan
Sinan

Reputation: 11563

Because it probably throws an exception, try this:

$(document).ready(function(){

  $("a[time-update]").click(function(event) {

    var time = new Date();
    $("#time").val(time);
    event.preventDefault();

  });

});

hope it helps, Sinan.

Upvotes: 0

MiffTheFox
MiffTheFox

Reputation: 21555

Add a click method to the button or link that will set the value of the form using a string gotten from the JavaScript Date object.

Upvotes: 2

Related Questions