Christina de L Christina de L - 5 months ago 11
HTML Question

JavaScript, document.getElementById not grabbing from form?

I'm attempting to create a datetime-local input that will submit into a function that will convert it into different types later on. I've been attempting to check whether the function I am using is receiving the user input by throwing it into an alert, however every time I get the alert, the information is not displayed, with "[object HTMLInputElement]" in its place. Clearly I must be doing something wrong if my bugtest isn't even working properly

Below is my form and my script.

<form>
Start Time:
<input type="datetime-local" id="start">
End Time:
<input type="datetime-local" id="end">
<input type="submit" value="Send" onclick="convert()">
</form>

<script>
function convert() {
var sd = new Date(); //start date
var sds = new String();
var ed = new Date(); //end date
var eds = new String();
var sd = document.getElementById("start");
alert(sd);
var sds = document.getElementById("end");
alert(sds);
}
</script>


Does anything obvious stick out?

Answer

Simply calling getElementById will return an HTMLInputElement object. To get its value, you need to call .value

var sd = document.getElementById("start").value;

and

var sds = document.getElementById("end").value;

You also declared the variable sd twice. Only once is necessary. This adds to the codebase and makes things less DRY. Also, instead of initializing a new string like this

var eds = new String();

Do this instead

var eds = "";

I updated and improved your code.

var startValue = document.getElementById("start-value");
var endValue = document.getElementById("end-value");

function convert() {
    var sd = new Date();   // start date
    var ed = new Date();   // end date
    var eds = new String();
    var sd = document.getElementById("start").value;
    startValue.innerHTML = sd;
    var sds = document.getElementById("end").value;
    endValue.innerHTML = sds;
}
<form>
    Start Time:
    <input type="datetime-local" id="start">
    End Time:
    <input type="datetime-local" id="end">
    <input type="submit" value="Send" onclick="convert()">
</form>

<p id="start-value"></p>
<p id="end-value"></p>