Calling functions in HTML forms
Having significant problems making a simple link between a form's buttons and javaScript functions.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="generator" content="HTML Tidy for Linux (vers 6 November 2007), see www.w3.org" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Examples of Strings</title>
<script type="text/javascript">
//<![CDATA[
// 开发者_如何学Pythondeclarations
//]]>
</script>
</head>
<body>
<h1>Basic Calculator</h1>
<form action="form_action.asp" method="get">
First Variable: <input type="text" name="tb1" /><br />
Second Variable: <input type="text" name="tb2" /><br />
Result: <input type="text" name="result" /><br />
<input type="button" name="b1" value="Submit" onclick="myAdd()" /><br />
</form>
<script type="text/javascript">
//<![CDATA[
<asp:Button id="b1" runat="server" OnClick="documment.myAdd()"></asp:Button>
function myAdd(tb1, tb2){
var result = tb1 + tb2;
alert(result);
return result;
}
//]]>
</script>
</body>
</html>
Button (b1) should return the values at tb1 and tb2. Note: ultimately it should represent the value at tb3, but for the purposes of debugging tb3 is doing nothing at the moment.
In a browser environment, window
is the global object, not document
.
You can also omit it, and the scope is automatically resolved to window
.
Also, you aren't passing the arguments to your function. You should just give them an id
attribute and reference that using document.getElementById()
.
Something like this should do it (provided you add the id
attribute as per code)...
window.onload = function() {
document.getElementById('my-form').onsubmit = function() {
document.getElementById('result').value = parseInt(document.getElementById('tb1').value, 10) + parseInt(document.getElementById('tb1').value, 10);
return false;
};
};
精彩评论