Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>
like image 742
benua Avatar asked Aug 22 '26 01:08

benua


1 Answers

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>
like image 116
Anant Kumar Singh Avatar answered Aug 24 '26 15:08

Anant Kumar Singh