Heim  >  Artikel  >  Web-Frontend  >  jQuery多个input求和的实现方法_jquery

jQuery多个input求和的实现方法_jquery

WBOY
WBOYOriginal
2016-05-16 16:14:121256Durchsuche

本文实例讲述了jQuery多个input求和的实现方法。分享给大家供大家参考。具体实现方法如下:

html页面代码如下:

<td> 
  <input name="add" id="add" readonly="readonly"/> 
</td> 
<pre name="code" class="html"><td> 
  <input name="add1" id="add1"/> 
</td> 
<td> 
  <input name="add2" id="add2"/> 
</td> 

jQuery部分代码如下:

<script> 
$("input[id^='add']").change(function(){ 
    var sum=0; 
    $("input[id^='add']").each(function(){ 
      var r = /^-&#63;\d+$/ ; //正整数 
      if($(this).val() !=''&&!r.test($(this).val())){ 
       $(this).val("");  //正则表达式不匹配置空 
      }else if($(this).val() !=''){ 
       sum+=parseInt($(this).val()); 
      } 
      document.getElementById("add").value=sum; 
      }); 
    }); 
</script> 

由于input属性为readonly,所以在浏览器中按Backspace删除该input的值时会出现页面返回的情况,解决方法可参照前面一篇《JQuery实现防止退格键返回的方法

希望本文所述对大家的jQuery程序设计有所帮助。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn