最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to calculate two input form fields and put the value in another without submitting the form using jquery? - Sta

programmeradmin5浏览0评论

I know this is an extremely basic question but I'm stuck on this. I have two input boxes and I want to calculate those inputs and show the result into another input (3rd one) immediately without the need of a submit button. I means, once I start entering the values into the input and the result will shows live in the 3rd input which is the represent the result...

<input type="text" class="input value1">
<input type="text" class="input value2">
<input type="text" disabled="disabled" id="result">

<script>
 $(document).ready(function(){
      var val1 = $(".value1").val();
      var val2 = $(".value2").val();
      $(".input").keyup(function(){
         $("#result").text(val1+val2);
       });
});
</script>

I know this is an extremely basic question but I'm stuck on this. I have two input boxes and I want to calculate those inputs and show the result into another input (3rd one) immediately without the need of a submit button. I means, once I start entering the values into the input and the result will shows live in the 3rd input which is the represent the result...

<input type="text" class="input value1">
<input type="text" class="input value2">
<input type="text" disabled="disabled" id="result">

<script>
 $(document).ready(function(){
      var val1 = $(".value1").val();
      var val2 = $(".value2").val();
      $(".input").keyup(function(){
         $("#result").text(val1+val2);
       });
});
</script>
Share Improve this question asked Oct 24, 2013 at 16:39 facemoifacemoi 451 gold badge1 silver badge5 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 11

Put val1 and val2 in keyup statement.

$(document).ready(function(){
    $(".input").keyup(function(){
          var val1 = +$(".value1").val();
          var val2 = +$(".value2").val();
          $("#result").val(val1+val2);
    });
});

Look at fiddle: http://jsfiddle/g7zz6/

Under the assumption of SUM as you stated, the inputs will be numberic in nature.

$(".input").on("change", function(){
    var ret = Number($(".value1").val()) + Number($(".value2").val());
    $("#result").val(ret);
}

just set the text value, also you need to parse them as other wise they will be concatenated as strings.

$(document).ready(function () {
    var val = parseInt($(".value1").val()) + parseInt($(".value2").val());
    $("#result").text(val);
});

Live Demo

 function addinput(){ 
   var x= Number(document.getElementById("first").value);
   var y= Number(document.getElementById("second").value);
   var z= Number(x+y);
   document.getElementById("l").value = Number(z);     
 }

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论