Dynamically check text input

余生长醉 提交于 2021-02-11 10:15:47

问题


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:

 $(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>")
    }
 });

Thx for you help!


回答1:


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("!")

instead of :

$(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.

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.

EDIT

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.

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.




回答2:


You should use .foucsout(). As soon as focus is lost from a text field, say, by pressing tab key to jump to next field or button. Test in .focusout() callback for length and append '!'

Also, refer to @zakinster solution. His solution will help you out in replacing '*' to '!'. As, I understood this, I suggested .focusout(), so that it replaces asterisk to exclamation when user has completed typing his input and his input can then be judged.



来源:https://stackoverflow.com/questions/16231100/dynamically-check-text-input

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!