将文本字段值与选择的值

时间:2017-09-11 11:12:47

标签: javascript jquery

如何将文本字段中的值与选择列表的值相乘?

我有以下HTML代码:



$(document).ready( function() {
$('#myForm').on('keyup', 'input', function() {
    var iSum = 0;
    $('#myForm input').each( function() {
       iSum = iSum + parseFloat($(this).val());
    });       
    $('#calculateSum').html(iSum);
});
});

<form id="myForm">
<input type="text" placeholder="Room length" /><br>
<input type="text" placeholder="Room width" />
<br>
<select>
  <option value="type-1">Type 1 (150,00€/m²)</option>
  <option value="type-2">Type 2 (155,00€/m²)</option>
</select><br>
  <div>
      <label for="calculateSum">Sum is</label>
      <span id="calculateSum">0</span> /m²
  </div>
  </form>
&#13;
&#13;
&#13;

我想将select-list的值乘以textfields的乘法结果。所以应该是房间长x房间宽x。 1型

3 个答案:

答案 0 :(得分:1)

function calculate() {
	var iSum = 1;
	$('#myForm input').each( function() {
		iSum *= parseFloat($(this).val());
	});       
	$('#calculateSum').html(iSum);
	var selectedValue = Number($("#values").val());
	$('#calculateValue').html(iSum * selectedValue);
}
$(document).ready( function() {
	$('#myForm input, #values').on('keyup change select', function() {
		calculate();
	});
	
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
<input type="text" placeholder="Room length" /><br>
<input type="text" placeholder="Room width" />
<br>
<select id="values">
  <option value="150.00">Type 1 (150,00€/m²)</option>
  <option value="155.00">Type 2 (155,00€/m²)</option>
</select><br>
  <div>
      <label for="calculateSum">Sum is</label>
      <span id="calculateSum">0</span> /m² <br />
      Totla: <span id="calculateValue">0</span> €
  </div>

答案 1 :(得分:1)

您可以使用解决方案https://jsfiddle.net/kq3ugctn/1/

&#13;
&#13;
updateCalc = function(){
  var iSum = 1;
  $('#myForm input').each( function() {
    if(isNaN(parseFloat($(this).val()))) {
      iSum *= 0;
    } else {
      iSum *= parseFloat($(this).val());
    }    
  });       
  iSum *= parseFloat($('select option:selected').data('value'));
  $('#calculateSum').html(iSum);
}

$('#myForm').on('keyup', 'input', function() {
  updateCalc();
});

$('select').on('change', function(){
  updateCalc();   
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm">
  <input type="text" placeholder="Room length" /><br>
  <input type="text" placeholder="Room width" />
  <br/>
  <select>
    <option value="type-1" data-value="15000" selected>Type 1 (150,00€/m²)</option>
    <option value="type-2" data-value="15500">Type 2 (155,00€/m²)</option>
  </select>
  <br>
  <div>
    <label for="calculateSum">Sum is</label>
    <span id="calculateSum">0</span> /m²
  </div>
</form>
&#13;
&#13;
&#13;

解决方案说明

updateCalc方法将被调用两次

  • input textbox更新
  • 选择选项更改。

如果未将值输入input文本框,则会将其视为 0

希望这会对你有所帮助。

答案 2 :(得分:1)

对此的简单回答是:

public form1()
{
    Commands obj = new Commands();
    InitializeComponent();
}