limiting the value that can be entered in the input

Asked

Viewed 1,335 times

4

I have a php variable that has a value that varies depending on the moment!! Example

1st moment $valor = 300

second moment $valor = 20

3rd moment $valor = 5300

fourth moment $valor = 1300

I also have an input, in this input can add any value, as long as it is below the value at the time you type. Here’s what I want to do!! If someone comes to enter a higher value in the input the value automatically changes pro maximo and not to what was typed!!

Example:

1st moment $valor = 300 || In this first moment the maximum value of the input may be only 300!! Only instead of 300 the user typed 301, at the same time I want these 301 turn 300, because it is the limit value that the user has!

  • I don’t quite understand the role of PHP. How do you keep the state between the different "moments"? With session variable? Javascript/jQuery only runs after PHP is finished.

  • php put more to signal what use it!

1 answer

8


Using jQuery I created this function that keeps listening to the event keyup (when the user releases a key). Inside the function I check the value.

$('#txtValor').on('keyup', function(event) {
  var valorMaximo = 300;

  if (event.target.value > valorMaximo)
    return event.target.value = valorMaximo;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Digite o valor: R$ <input type="text" id="txtValor">

  • Strange, it is not working on my pc the code!

  • Are you importing the jQuery lib? Note that I am listening to the input with the id "txtValor".

  • yes yes!! I put everything right!! I even copied your code exactly the way it is to test and it didn’t even work like that!

  • If there is a reference error put code inside the tag <script>at the bottom of the page or use the function $(Document). ready(), why maybe the page was not fully loaded, so the function cannot find the field.

  • I put in the end and it worked!! Thanks!! But because it happens it happens?

  • 1

    Ivan, it is because the following happens: You are trying to listen to an event of an element that has not yet been "loaded", as the function was at the top (before the field) it cannot see the field after it loads (because it tried and failed at first). Using one of these two solutions works because: 1) Using the $(document).ready() it will only load your script after the page is ready. 2) Your field has already been loaded so the script sees the field.

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.