我现在有三个文本框:
<html>
   <body>
         <form>
             第一个数:<input type="text" name="first" id="first">
              第二个数:<input type="text" name="second" id="second">
              第三个数:<input type="text" name="third" id="third">             总计: <input type="button" name="sum" id="sum" readonly="readonly">
         </form>
   </body>
</html>现在要求用jqery来实现,三个文本框输入值相加为总计中得值,只要其中任何一个文本框中得值发生变化,总计中的值相应发生变化。

解决方案 »

  1.   


    <body>
    <form>
      第一个数:<input type="text" name="first" id="first" onchange="fn()">
      第二个数:<input type="text" name="second" id="second" onchange="fn()">
      第三个数:<input type="text" name="third" id="third" onchange="fn()">  总计: <input type="type" name="sum" id="sum" readonly="readonly">
      </form>
    </body>
    <script>
    var fEl = $("#first"),
    sEl = $("#second"),
    tEl = $("#third");
    function fn(){
    $("#sum").val(+fEl.val() + +sEl.val() + +tEl.val());
    }</script>
      

  2.   


     这个写的偏离jquery 的本意了吧
    <html>  <body>
      <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.min.js"></script>
      <script>
       $(document).ready(function(){
    $('input').keyup(function(){
    var first=parseInt($.trim($('#first').val()))||0;
    var second=parseInt($.trim($('#second').val()))||0;
    var third=parseInt($.trim($('#third').val()))||0;
    $('#sum').val(first+second+third);
    });

    });
      </script>
      <form>
      第一个数:<input type="text" name="first" id="first">
      第二个数:<input type="text" name="second" id="second">
      第三个数:<input type="text" name="third" id="third">  总计: <input type="button" name="sum" id="sum" readonly="readonly">
      </form>
      </body>
    </html>