user3705672
user3705672

Reputation: 65

How to deduct a total number from a looped input type=number

Here's my code:

<html>

<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.js"></script>
<script type="text/javascript">//<![CDATA[ 
$(window).load(function(){
$(".sub").focusout(function() {
    $("#answer").html('');
    var num = $("#num").val();
    var answer = 100 - num;
    $("#answer").html(answer);
});
});//]]>  
</script>
</head>

<body>
<p id='answer'> 100 </p>
<?php
    $db=mysql_connect("localhost","root","") or die("Could not connect to database");
    mysql_select_db("cb_client_database") or die("could not select database");
    $query = "SELECT * FROM ra_rooms WHERE Category = 'Double Deluxe Room'";
    $result=mysql_query($query, $db) or die(mysql_error($db));

    echo "<table>";

    while ($row = mysql_fetch_array($result))
    {
    extract($row);
?>
<tr><td><input type='number' max='<?phpecho"$Min_Capacity";?>' min='0' name='num' id=num class=sub><?phpecho"$RoomNumber";?></td></tr>


 <?php
     } 
     echo "</table>";
 ?>
</body>
</html>

For example: If I have four(4) records(This depends on how many records my database have), it should generate 3 more variables so the calculation should be like this:

 var answer = 100 - (num + num2 + num3 + num4);

The problem is, I don't know how to. Please help me.

Upvotes: 1

Views: 266

Answers (2)

Mr7-itsurdeveloper
Mr7-itsurdeveloper

Reputation: 1631

1) write echo"$RoomNumber"; in value of input.

2)use double quotes for id and class input.

3.try with counter check below php code .id of input will increase auto.

 <script>  

  var num1 = $('#num1').val();  
    var num2 = $('#num2').val();  
    var num3 = $('#num3').val();  
var num4 = $('#num4').val();  
    var answer = 100 - (num1+num2+num3+num4 );
    </script>  

<?php   
    $x=1; 
    while($x<=4)   //4 or count($result)
    {

    ?>  
<tr><td><input type='number'  min='0' name='num' value="<?phpecho"$RoomNumber";?>" id="num<?php echo $x;?>" class="sub"></td></tr>

<?php
$x=$x+1;  

}
?>

Upvotes: 0

Ja͢ck
Ja͢ck

Reputation: 173542

First, remove id="num" from the <input> elements (you can't have more than one unique identifier per document).

Then, update your code a little to calculate the sum over multiple elements:

var num = 0;
$('input.sub').each(function() {
    num += parseInt(this.value, 10);
});
var answer = 100 - num;
$("#answer").html(answer);

I've made the assumption that "input.sub" matches the right input elements.

Upvotes: 1

Related Questions