简体   繁体   中英

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> 

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> 

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM