benua
benua

Reputation: 195

Change input value dynamically with jQuery

I'm trying to change input value and display an alert based on value written by the user. Now it doesn't work unless it goes out of focus. Can I make it work immediately without any waiting period?

jQuery('input').on('change', function () {
    var myInput = jQuery(this);
    if (myInput.val() < 0.2 ) {
        myInput.val('0.2');
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="">
<p class="alert" style="display: none">minimum value is 0.2</p>

Upvotes: 3

Views: 1199

Answers (2)

sergdenisov
sergdenisov

Reputation: 8572

What I'd do in this case:

  1. input event instead of change to "make it work immediately without any waiting period";

  2. Add another type of error for the case when your value is an empty or incorrect number.

const $errors = $('.alert');

$('input').on('input', function(e) {
    const $input = $(e.target);
    const value = Number($input.val());
    let errorType = '';
    
    if (!value) {
      errorType = 'required';
    } else if (value < 0.2) {
      errorType = 'min';
      $input.val(0.2);
    }
    
    $errors.addClass('alert_hidden');
    $errors.filter(`[data-type="${errorType}"]`).removeClass('alert_hidden');
});
.alert {
  background-color: red;
}

  .alert_hidden {
    display: none;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="">
<p class="alert alert_hidden" data-type="min">minimum value is 0.2</p>
<p class="alert alert_hidden" data-type="required">value is required</p>

Upvotes: 0

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72289

1.You can use input or keyup method.

2.Also .val() will give you a string value, so comparing it with 0.2 convert it to float with the help of parseFloat()

like below:-

Example 1:-

jQuery('input').on('input', function () {
    var myInput = jQuery(this);
    if (parseFloat(myInput.val()) < 0.2 ) {
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="">
<p class="alert" style="display: none">minimum value is 0.2</p>

Example 2:-

jQuery('input').on('keyup', function () {
    var myInput = jQuery(this);
    if (parseFloat(myInput.val()) < 0.2 ) {
        jQuery('.alert').css('display', 'block')
    }
    else {
        jQuery('.alert').css('display', 'none')
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input value="">
<p class="alert" style="display: none">minimum value is 0.2</p>

Upvotes: 2

Related Questions