1

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.

0

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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()
 }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.