简体   繁体   中英

JavaScript getElementById().value returning a value but giving “Undefined” when assigned to variable

I am trying to get a form to submit via AJAX request.

There are many forms on the pages and each form has a different id tag for the relevant input field:

My JavaScript needs to be able to differentiate between each form and I am doing this by the id tag.

When I run in chrome's console I get my expected value:

document.getElementById("form-quantity-1").value;
"1"

When I assign to a variable:

var quan = document.getElementById("form-quantity-1").value;
undefined

I am at a loss as to why.

The expression

var x = 1

doesn't return a value. The console returns the value of the expression you just typed, and since var x = 1 doesn't have a value, the console prints undefined . However, the variable is still set, which you can see if you just enter the name of the variable:

>> x
1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM