Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to change back the original value in my form after modified

i created input named "quantity" that has a value of 30, and the 2nd input named "sold"

$(document).ready(function() {
  $("#sold,#quantity").keyup(function() {
    var total = 0;
    var y = Number($("#quantity").val());
    var x = Number($("#sold").val());
    var total = y - x;
    $("#quantity").val(total); // the result will be showed in "quantity"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table width="100">
  <tr>
    <td>Quantity</td>
    <td>Sold</td>
  </tr>
  <tr>
    <td><input type="text" id="quantity" value="30"></td>
    <td><input type="text" id="sold"></td>
  </tr>
</table>

should looks like this

Quantity: 30 Sold: (input something)

now i added some script that any value inputs from sold will subtract the value from quantity automatically

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

example output:

Quantity: 28 Sold: 2 
// 30 is the original value of quantity subtracted by 2 is 28

now for example if i will clear my input on sold the quantity its still has the value of 28

Quantity: 28 Sold: (cleared/removed)

my question what should i do to return the original value of quantity which is 30 even i clear my input in sold

expected output:

Quantity: 30 Sold: (cleared/removed)

>Solution :

You can save the value

$(document).ready(function() {
  const def = $("#quantity").val()
  $("#sold,#quantity").keyup(function() {
    var total = 0;
    var x = Number($("#sold").val());
    var total = def - x;
    $("#quantity").val(total); // the result will be showed in "quantity"
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<table width="100">
  <tr>
    <td>Quantity</td>
    <td>Sold</td>
  </tr>
  <tr>
    <td><input type="text" id="quantity" value="30"></td>
    <td><input type="text" id="sold"></td>
  </tr>
</table>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading