Please consider the following non-working HTML document:
<html>
<body>
<form action="" method="GET" onsubmit="return f(this);">
<input type="text" name="bar" value="" />
<input type="button" name="foo" value="foo" />
</form>
</body>
<script type="text/javascript">
function f(x) {
alert(x.bar);
}
</script>
</html>
What I am trying to achieve is that when either (a) the foo button is pressed; or (b) enter is pressed while the text input has focus; then the function f is called with the content of the s text input - and the browser should otherwise stay on the same page after f returns.
How can I achieve this?
Please consider the following non-working HTML document:
<html>
<body>
<form action="" method="GET" onsubmit="return f(this);">
<input type="text" name="bar" value="" />
<input type="button" name="foo" value="foo" />
</form>
</body>
<script type="text/javascript">
function f(x) {
alert(x.bar);
}
</script>
</html>
What I am trying to achieve is that when either (a) the foo button is pressed; or (b) enter is pressed while the text input has focus; then the function f is called with the content of the s text input - and the browser should otherwise stay on the same page after f returns.
How can I achieve this?
Share Improve this question edited Jul 8, 2012 at 21:55 Jashwant 29k16 gold badges76 silver badges108 bronze badges asked Jul 8, 2012 at 20:07 Andrew TomazosAndrew Tomazos 68.9k44 gold badges205 silver badges345 bronze badges 1- What exactly does not work with that document? – Bergi Commented Jul 8, 2012 at 20:19
2 Answers
Reset to default 3You should use a submit input rather than a button input, and to get the text from text input you use the value property and return false to prevent the form from submitting
<html>
<body>
<form action="" method="GET" onsubmit="return f(this);">
<input type="text" name="bar" value="" />
<input type="submit" name="foo" value="foo"/>
</form>
<script type="text/javascript">
function f(x)
{
alert(x.bar.value);
return false;
}
</script>
</body>
</html>
FIDDLE
Just call it with the value instead of the form element?
onsubmit="return f(this.bar.value);"
To prevent the sending of that page, you can return false
from f
.
But it would be much cleaner to use a proper event handler instead of that onsubmit-attribute. Read more on them here.
<html>
<body>
<form id="inputform" action="" method="GET">
<input type="text" name="bar" value="" />
<input type="button" name="foo" value="foo"/>
</form>
<script type="text/javascript">
function f(x) {
alert(x.bar);
}
var form = document.getElementById("inputform");
form.onsubmit = function(event) {
var x = f(form.bar.value);
if (!x)
event.preventDefault();
};
</script>
</body>
</html>