ngchongpeng
ngchongpeng

Reputation: 25

2 different javascript statements returning different values when it should be the same

I can't seem to figure out this inconsistency in the code below. Shouldn't (x.value) be the same as (y)? Why are they returning different values?

Thanks in advance for the help.

html:

<form>
    <input name="startDate" type="date" value="">
</form>

<button onclick="getDate()">click</button>

javascript:

var x = $("input[name=startDate]")[0];
var y = $("input[name=startDate]")[0].value;

function getDate() {

    console.log(x.value); // returns what i've chosen in the datepicker (eg. 2018-05-14)
    console.log(y); // returns an empty string
}

Upvotes: 2

Views: 48

Answers (4)

Anadi Sharma
Anadi Sharma

Reputation: 295

This is happening because as soon as your page is loaded in DOM, your javascript code is also initialized. Variable x has the input element, whereas y already is populated with an empty string because there was no default value at the initialization. So, definitely you can never see both the values as same.

Upvotes: 0

Beomi
Beomi

Reputation: 1727

Because y is FIXED value.

When you're calling DOM object with .value, it is not reactive object, but fixed value.

When you're calling x, it just points real HTML element. so you can get x's value with x.value in getDate function.

However, as you're already declared y as the value of HTML DOM object, so it won't be updated in getDate function.

Upvotes: 0

Rick van Lieshout
Rick van Lieshout

Reputation: 2316

This is actually rather simple.

As soon as the script loads y is assigned a value on line 2, at this point the value of the input is an empty string as you haven't had the change to type anything yet.

The function gets executed when you click the button, at this point you have entered something in the input field so x.value will return whatever you entered in the input field.

y will still have the original value assigned on line 2 since you never update it.

you could update y like so:

var x = $("input[name=startDate]")[0];
var y = $("input[name=startDate]")[0].value;

function getDate() {
    y = $("input[name=startDate]")[0].value; // assign current value

    console.log(x.value); // returns what i've chosen in the datepicker (eg. 2018-05-14)

    console.log(y); // returns what you want
}

Upvotes: 0

gurvinder372
gurvinder372

Reputation: 68373

x is HTMLInputElement object on which you are invoking value, which will give you latest value of x.

On the other hand, y is the String value of the same HTMLInputElement at the time of initialization of variable y, so it won't get updated automatically.

Upvotes: 2

Related Questions