2017-01-28 61 views
1

我需要使用jQuery計算輸入值。如果輸入的GValue是100和選定的百分比爲10%,則在最終的值它應該顯示的110的合計值這應該是這樣的100 * 10%+ 100 = 110。使用jQuery計算HTML

value 
<input type="text" name="gvalue" class="input" required/> 

Percentage 
<select name="percent" id="percent" class="input" onchange="setStates();"> 
    <option value="Country" selected>Select Percentage</option> 
    <option value="5">5</option> 
    <option value="10">10</option> 
    <option value="15">15</option> 
</select> 

Final Value 
<input type="text" name="flvalue" class="input" id="#total" required/> 

回答

1

使用的事件處理程序並根據輸入值計算總和。

// bind event handler to both input and select tag 
 
$('#percent,#input').on('change input', function() { 
 
    // parse input field value, if NaN treat as 0 
 
    var val = Number($('#input').val()) || 0, 
 
    // parse select field value, if NaN treat as 0 
 
    per = Number($('#percent').val()) || 0; 
 
    // calculate and update the total 
 
    $('#total').val(val + val * per/100) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
value 
 
<input type="text" name="gvalue" id="input" class="input" required/>Percentage 
 
<select name="percent" id="percent" class="input"> 
 
    <option value="Country" selected>Select Percentage</option> 
 
    <option value="5">5</option> 
 
    <option value="10">10</option> 
 
    <option value="15">15</option> 
 
</select> 
 

 
Final Value 
 
<input type="text" name="flvalue" class="input" id="total" required/>

+0

我需要它有另一個查詢<選擇name = onchange事件「百分比「 id =「percent」class =「input」onchange =「setStates();」> – udhay

+0

@udhay在該功能中做同樣的工作 –

+0

感謝兄弟,這不是一個錯誤還有另一個錯誤 – udhay

0
$(document).on('change', 'select[name="percent"]', function(){ 
    var total = parseInt($('input[name="gvalue"]').val())/ (parseInt($('select[name="percent"]').val())/100) + 100) 
$('input[name="flvalue"]').val(total); 
    }) 
0

你的HTML:

value 
<input type="text" name="gvalue" id="gvalue" class="input" required/> 

Percentage 
<select name="percent" id="percent" class="input" onchange="setStates();"> 
    <option value="Country" selected>Select Percentage</option> 
    <option value="5">5</option> 
    <option value="10">10</option> 
    <option value="15">15</option> 
</select> 

Final Value 
<input type="text" name="flvalue" class="input" id="total" required/> 

你的JavaScript代碼:

<script> 
    function setStates(){ 
     var gvalue = $('#gvalue').val(); 
     if(gvalue){ 
      var gvalue = parseInt(gvalue); 
      var percent = parseInt($('#percent').val()); 
      var final = (gvalue*percent/100)+100; 
      $('#total').val(final); 
     } else { 
      $('#gvalue').css('border-bottom-color','red'); 
     } 
    } 
</script>