cmf05
cmf05

Reputation: 411

JS, Getting datetime object from html form

I have an html form

<form onsubmit="return test();">
   Start:<input type="date" name=start><br>
   End:<input type="date" name=end><br>
   Type: <select name = "type">
   <input type="submit" value = "Submit"></input>
</form>

and am trying to access the date as an ISOString in a javascript function

function test() {
    ...
    const start = oForm.elements["start"].value.toISOString()
    ...

}

However, this doesn't work. Any guidance would be greatly appreciated.

Upvotes: 1

Views: 1224

Answers (2)

Artem Kolodko
Artem Kolodko

Reputation: 409

You can pass form context and form values to window-context (or another if you prefer) function, for example:

<form onsubmit="return test(this);">
  Start:<input type="date" name="start"/><br>
  End:<input type="date" name="end"/><br>
  Type: <select name = "type"/>
  <input type="submit" value = "Submit"/>
</form>

And the function is

window.test = function(data) {
 let start = data.elements['start'].value;
 console.log(start); // check value, 2017-01-01 for example
 return {
   start: new Date(start).toISOString()
 }
}

Upvotes: 0

treyhakanson
treyhakanson

Reputation: 4911

I'd do it like this, by first converting the value to a Date object:

const start = document.querySelector('input[name="start"]');
const date = new Date(start.value).toISOString();

As a side note, if you'll be working with a lot of dates I'd checkout moment.js. It has a lot of really useful functions for handling and manipulation dates and times.

Upvotes: 1

Related Questions