开发者

how to add assign the value and make an addition in javascript

开发者 https://www.devze.com 2023-02-20 06:30 出处:网络
<input name=\"\" type=\"button\" value=\"300\" onclick=\"document.all.t1.value=this.value\" /> <input name=\"t1\" type=\"text\" id=\"t1\"/><br /开发者_StackOverflow社区>
<input name="" type="button" value="300" onclick="document.all.t1.value=this.value" />
<input name="t1" type="text" id="t1"/><br /开发者_StackOverflow社区>

<input name="" type="button" value="400" onclick="document.all.t2.value=this.value" />
<input name="t2" type="text"  id="t2"/><br />
<script>
function add(){
    document.getElementById("t3").value = Math.floor(document.getElementById("t1").value) +
                                          Math.floor(document.getElementById("t2").value);
}
</script>

<input name="" type="button" value="add" onclick="add" />
<input name="t3" type="text" id="t3"/>

the above code is bad., expect some to correct it. thank you.

when click 300, the 300 vill in the first textbox, the same as 400, then click add button. the third textbox shoew 700


Your "onclick" has to look like this:

<input name="" type="button" value="add" onclick="add()" />

References to document.all won't work in browsers other than Internet Explorer, so you should change those to use document.getElementById() instead.


You'll have to call the function rather than reference it.

That is, use:

<input name="" type="button" value="add" onclick="add()" />
                                                    /|\
                                                     |
-------------------------------------------------------


<script type="text/javascript">
function add(){
    document.getElementById("t3").value = parseInt(document.getElementById("t1").value) +
                                          parseInt(document.getElementById("t2").value);
}
</script>
<input name="" type="button" value="300" onclick="document.getElementById('t1').value=this.value" />
<input name="t1" type="text" id="t1"/><br />

<input name="" type="button" value="400" onclick="document.getElementById('t2').value=this.value" />
<input name="t2" type="text"  id="t2"/><br />

<input name="" type="button" value="add" onclick="add()" />
<input name="t3" type="text" id="t3"/>

http://jsfiddle.net/AQYJh/

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号