Saturday 15 August 2015

Simple Javascript rectangle area function -


I am writing a simple task to calculate the area of ​​a rectangle ...

Here is my code:

  & lt; Form id = "rectangleform" method = "post" & gt; & Lt; H1 & gt; Calculate the area of ​​a rectangle: & lt; / H1> & Lt; Div & gt; & Lt; Label = "width" & gt; Width & lt; / Label & gt; & Lt; Input type = "text" name = "width" id = "width" value = "1.00" /> & Lt; / Div & gt; & Lt; Div & gt; & Lt; Label = "height" & gt; Height & lt; / Label & gt; & Lt; Input type = "text" name = "height" id = "height" value = "1.00" /> & Lt; / Div & gt; & Lt; Div & gt; & Lt; Label = "area" & gt; Area & lt; / Labels & gt; & Lt; Input type = "text" name = "domain" id = "rectarea" value = "0.00" /> & Lt; / Div & gt; & Lt; Div & gt; & Lt; Input type = "submit" value = "calculate" id = "submit" /> & Lt; / Div & gt; & Lt; / Form & gt; & Lt; Script & gt; Function rectangle () {'strict experiment'; Var region; Var width = document.getElementById ('width'). Values; Var height = document. GetElementById ('height'). Values; Total = width * height; Document.getElementById ('Area'). Value = total; return false; } Function init () {'strict experiment'; Var Rectiform = document.getElementById ('Rectiform Form'); Rectangle. Resource = rectangle (); } Window.onload = init (); & Lt; / Script & gt;   

I am getting an "unsolicited type" error: the 'value' of the property can not be read. Error on Var Width Line I do not understand why anybody can leave any information or solution?

There are three problems with your code.

First of all, at the following lines:

  rectangle. Resource = rectangle (); Window.onload = init ();   

... you are calling to rectangle () and init () and Assigning them are the resulting onsubmit and onload handler, which means that tasks are run once and do not run in response to form submissions events. You need to remove the parentheses so that the function can be assigned as a handler:

  rectangleForm.onsubmit = rectangle; Window.onload = init;   

Secondly, in your area input, there is id = "rectarea" , but in your code you use document.getElementById ("area") - You have to match these up.

Thirdly, there is 'strict use' in your function; Instructions, but then your code is not really strict because you do not declare total variable then change:

  total = width = height;   

to:

  var total = width * height;   

With these changes, your code has been implemented as shown in this demo:

No comments:

Post a Comment