动态检查文本输入 [英] Dynamically check text input

查看:42
本文介绍了动态检查文本输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个输入表单,该表单在每个必填字段的框后都有一个星号.如果用户输入字符串,星号应更改为感叹号.现在,每次用户键入字母时,javascript代码都只会添加一个感叹号.

I'd like to create an input form that has an asterisk after the box for each required field. If the user enters a string the asterisk should change to a exclamation mark. Right now the javascript code just adds an exclamation mark every time the user types a letter.

HTML:

<form name="form1">
<ul>
<li><input type='text' name ='text1' required placeholder="required"/></li>
<li><input type='text' name ='text1' required placeholder="required"/></li>
<li><input type='text' name ='text1' placeholder="not required"/></li>
</ul>
</form>

JAVA/JQUERY:

JAVA/JQUERY:

 $(function() {
        $('input:required').after( "<span>*</span>" );  

    });

 $('input:required').keyup(function(){
    var dInput = this.value;
    if(dInput.length > 0)
    //if($('input:required').is(':valid'))
    {
        $(this).after("<span>!</span>")
    }
 });

谢谢您的帮助!

推荐答案

您的主要问题是,您每次 .after 都会在您每次添加 span 元素,您可以使用 .parent().children("span")取回先前创建的span元素,然后更改其内容:

Your main problem is that your .after will add a span element each time you call it, you can get back the previsouly created span element using .parent().children("span")and then change its content :

 $(this).parent().children("span").text("!")

而不是:

$(this).after("<span>!</span>")

这是更正代码的最简单方法,但可能不是执行所需操作的最佳方法.

This is the simplest way to correct your code, but is probably not the best way to do what you want.

$('input').keyup()是用于全面控制实时验证的好方法,但是您也可以查看

The $('input').keyup() is a good approach for a full-control real time validation, but you could also take a look at the validation plugin of jQuery.

编辑

使用 span id而不是浏览DOM树的示例,这将允许您将 span 标记移动到HTML树中的任何位置而不会破坏JavaScript代码:

Example using a span id instead of navigating through the DOM tree, this would allow you to move the span tag anywhere in the HTML tree without breaking the JavaScript code :

$(function() {
    $('input:required').each(function(index) {
        var id = this.form.name+this.name+"mark";
        $(this).after( "<span id='"+id+"'>*</span>" ); 
    });
});

$('input:required').keyup(function(){
    if(this.value.length > 0) {
        var id = this.form.name+this.name+"mark";
        $("#"+id).text("!");
    }
});

请注意,要使此功能起作用,您的输入在表单内应具有唯一的名称.

Note that for this to work, you inputs should have unique names inside your form.

还要注意, span 标记及其对应的 id 可以用HTML静态编写,也可以由服务器生成,而不是由客户端在JavaScript中生成.

Also note that the span tags and their corresponding id could be statically written in the HTML or generated by the server instead of being generated by the client in JavaScript.

这篇关于动态检查文本输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆