I’m using the following HTML and JavaScript to display the value of the #username <input> element:
<form action="#" method="post">
Username: <input type="text" name="username" /><br />
Password: <input type="password" name="password" /><br />
<input class="test" type="submit" id="thing" value="Log In" />
</form>
$(document).ready(function() {
$('input#thing').on('click', function() {
var name = $('#username').val;
alert(name);
});
});
When I run it in my browser, I get an alert saying
function (value) {
var hooks, ret, isFunction, elem = this[0];
if (!arguments.length) {
if (elem) {
hooks = jQuery.valHooks[elem.type] ||
jQuery.valHooks[elem.nodeName.toLowerCase()];
if (hooks &&
"get" in hooks &&
(ret = hooks.get(elem, "value")) !== undefined) {
return ret;
}
ret = elem.value;
return typeof ret === "string" ? ret.replace(rreturn, "") : ret == null ? "" : ret;
}
return;
}
isFunction = jQuery.isFunction(value);
return this.each(function (i) {var val, self = jQuery(this);if (this.nodeType !== 1) {return;}if (isFunction) {val = value.call(this, i, self.val());} else {val = value;}if (val == null) {val = "";} else if (typeof val === "number") {val += "";} else if (jQuery.isArray(val)) {val = jQuery.map(val, function (value) {return value == null ? "" : value + "";});}hooks = jQuery.valHooks[this.type] || jQuery.valHooks[this.nodeName.toLowerCase()];if (!hooks || !("set" in hooks) || hooks.set(this, val, "value") === undefined) {this.value = val;}});
}
When it should be saying what the typed username is.
What’s happening?
The following code assigns the function
valto the variablename.You’re then passing the function into
alert. If you want to pass the value in the text box, you have to invoke the function and pass its return value: