简体   繁体   English

使用jQuery动态更改输入值

[英]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. 1.您可以使用inputkeyup方法。

2.Also .val() will give you a string value, so comparing it with 0.2 convert it to float with the help of parseFloat() 2. .val()会给你一个字符串值,所以将它与0.2比较,在parseFloat()的帮助下将其转换为float

like below:- 如下: -

Example 1:- 例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:- 例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"; input事件,而不是change为“使它立即工作,而无需任何等待期”;

  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> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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