如何从jQuery中添加的输入字段中获取值

时间:2018-06-13 12:43:05

标签: jquery

我有一个值示例50.如果我的值50很小,那么应该添加一个新字段,然后从添加的字段中取值,并且这两个值都等于50,然后添加新字段并再次获取值并继续..当我的价值从50开始变大。

请建议我......



$(function(){
  $('button').click(function(){
    var inMain = $('#mainNumber').val();
    var inMain1 = $('#mainNumber1').val();
    var inMain2 = $('#mainNumber2').val();
    var inMain3 = $('#mainNumber3').val();
    var inMain4 = $('#mainNumber4').val();
    var inMain5 = $('#mainNumber5').val();
				
    if(inMain<36){
      $('.my1box').show();
    } else if((inMain+inMain1) < 36) {
      $('.my2box').show();
    } else if((inMain+inMain1+inMain2) < 36) {
      $('.my3box').show();
    }	
  });
});
&#13;
[class$="box"] {
  display: none;
  margin-bottom: 10px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my">
  Main <input type="number" id="mainNumber">
</div>

<div class="my1box">
  1 <input type="number" id="mainNumber1">
</div>

<div class="my2box">
  2 <input type="number" id="mainNumber2">
</div>

<div class="my3box">
  3 <input type="number" id="mainNumber3">
</div>
<div class="my4box">
  4 <input type="number" id="mainNumber4">
</div>
<div class="my5box">
	5 <input type="number" id="mainNumber5">
</div>

<button>Submit</button>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:1)

您可以使用解决方案

&#13;
&#13;
$('button').click(function() {
  var total = 0;
  var inputs = $('input');
  for(var i=0; i<inputs.length; i++){
    total += parseInt($(inputs[i]).val());
  }
  if(total < 50) {
    $('.my1box').append(`<input type="number">`);
  } else {
    console.log("Finally your total score more than 50, Total Score:", total);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my">
  Main <input type="number">
</div>

<div class="my1box"></div>

<button>Submit</button>
&#13;
&#13;
&#13;

希望这会对你有所帮助。

说明:您的新输入将附加到my1box容器中。

只需遍历所有输入&amp;添加值然后检查总值。如果该值小于50,则再向my1box容器添加一个输入框。

更新回答

&#13;
&#13;
$('button').click(function() {
  var total = 0;
  var inputs = $('input.month');
  for(var i=0; i<inputs.length; i++){
    total += parseInt($(inputs[i]).val());
  }
  if(total < 36) {
    $('.my1box').append(`
      <input type="text" placeholder="Current Address" />
      <br/>Month
      <input type="number" class="month">`);
  } else {
    console.log("Finally your total score more than 36, Total Score:", total);
  }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="my">
  <input type="text" placeholder="Current Address" />
  <br />
  Month <input type="number" class="month">
</div>

<div class="my1box"></div>

<button>Submit</button>
&#13;
&#13;
&#13;