Henrik Kwok
Henrik Kwok

Reputation: 99

check input number whether bigger than certain value by using javascript

I am trying to do some calculation in page, however, it doesn't work, I have tried the following code, does anyone can tell me the correct answer?

For example, when I enter a number then it will do one of the calculation.

<table><tr><td>
<input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="">
</td><td>
<input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
<input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
<input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>"> 
<input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
</td></tr></table>
<script>
$(document).ready(function () {
var total = Number($("#per_pax").val());
if(total >= 20) {
$("#sum_tlcost,#sum_htl_pp,#sum_coach,#per_pax").keyup(function () {
if (parseInt($("#per_pax").val()) >= 20) {
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) / Number($("#per_pax").val()) + Number($("#sum_coach").val()) / Number($("#per_pax").val()));
)}else{
$("#pax").val(Math.round(Number($("#sum_htl_pp").val()) + Number($("#sum_tlcost").val()) + Number($("#sum_coach").val())))
}
})}})
</script>

Upvotes: 0

Views: 1156

Answers (1)

DynasticSponge
DynasticSponge

Reputation: 1441

I'm not overly fond of the jquery keyup calls... so here's a snippet that should call your function using normal DOM event calls. The input event triggers as they type.. which should be similar to what you're trying to do with the keyups... I also cleaned up the function itself to make it more readable for presentation.

function onInputChange() {
  var perPax = parseInt($("#per_pax").val());
  var tlCost = Number($("#sum_tlcost").val());
  var htlPP = Number($("#sum_htl_pp").val());
  var coach = Number($("#sum_coach").val());
  var newValue = 0;
  if (perPax < 20) {
    newValue = (htlPP + tlCost) / (perPax + (coach / perPax));
  } else {
    newValue = htlPP + tlCost + coach;
  }
  $("#pax").val(Math.round(newValue))
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td>
      <input name="per_pax" size="2" style="border-style:none" type="text" id="per_pax" value="" oninput="onInputChange()">
    </td>
    <td>
      <input name="sum_tlcost" type="hidden" id="sum_tlcost" value="<?php echo $tl_cost;?>">
      <input name="sum_htl_pp" type="hidden" id="sum_htl_pp" value="<?php echo $sum_htl_pp;?>">
      <input name="sum_coach" type="hidden" id="sum_coach" value="<?php echo $sum_coach;?>">
      <input name="pax" size="5" readonly="readonly" type="text" id="pax" value="">
    </td>
  </tr>
</table>

Upvotes: 1

Related Questions