简体   繁体   中英

How to prompt a message in textarea if input is more than 200 characters

How to prompt an error message in textarea if input is more than 200 characters. I am trying maxLength attribute. But it stops taking input. I dont want that. I want an error message there

Try writing a Jquery function which is called on the input change using the onchange attribute. Then use var messageTxt = $("#yourelementid").value(); If(messageTxt.length() > 200) { alert("input is more than 200 characters"); } var messageTxt = $("#yourelementid").value(); If(messageTxt.length() > 200) { alert("input is more than 200 characters"); }

<style type="text/css">
    .input-error ::-webkit-input-placeholder { /* WebKit, Blink, Edge */
        color:    red;
    }
    .input-error :-moz-placeholder { /* Mozilla Firefox 4 to 18 */
       color:    red;
       opacity:  1;
    }
    .input-error ::-moz-placeholder { /* Mozilla Firefox 19+ */
       color:    red;
       opacity:  1;
    }
    .input-error :-ms-input-placeholder { /* Internet Explorer 10-11 */
       color:    red;
    }
</style>

<div class="text-wrapper">
    <textarea id="infoText" placeholder="Type your text"></textarea>
</div>

<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js">
</script>
<script type="text/javascript">
    $(document).ready(function(){
        $('#infoText').bind('input propertychange', function() {
                    if($(this).val().length>4){
                        $(this).parent(".text-wrapper").addClass("input-error");
                        $(this).attr("placeholder","Text cannot exceed more than 200 characters")
                        $(this).val("");
                    }
                    else{
                        $(this).parent(".text-wrapper").removeClass("input-error")  
                    } ;

        });
    });
</script>

since your post has an angular tag, I am assuming you are using angular. In general, you can put a watch on the textarea model.

$scope.$watch('yourTextAreaModel', function(newVal) {
    if(newVal.length > 200){
    alert("input cannot be more than 200 characters");
    }
})

*You might not even need a watch but it depends on your application.

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