javascript to prevent writing into form elements a

2019-08-24 18:17发布

问题:

I use utf8_unicode_ci collation for my database, tables and table rows.

My site language will have uncommon characters like ş, Ğ, ö, ü, ç, İ

I have server side verification & validation rules however for visitor comfort, I want to use a javascript code that:

1-) prevent writing into form input after n utf8 characters while achieving a live countdown.

2-) I need to easily populate the javascript function since different form inputs have different values of n in the same html page

I searched for my aim and unfortunately I only could find a partial thingy from SO given below (Count bytes in textarea using javascript)

it counts how long in bytes a textarea is when UTF8.

getUTF8Length: function(string) {
    var utf8length = 0;
    for (var n = 0; n < string.length; n++) {
        var c = string.charCodeAt(n);
        if (c < 128) {
            utf8length++;
        }
        else if((c > 127) && (c < 2048)) {
            utf8length = utf8length+2;
        }
        else {
            utf8length = utf8length+3;
        }
    }
    return utf8length;
 }

I also created a sample and simple HTML 5 form on http://jsbin.com/fafonimo/3/edit which is given below also (some answerers may want to utilize):

HTML

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>JS Bin</title>
  </head>
  <body>
    <form method="post" action="#">
      <!--Fıstıkçı Şahap öğlen ülüküsü çerçöp-->
      <!--35 characters above-->
      <label class="c1" for="id-input">NAME OF THE AUTHOR</label>
      <input class="c1" type="text" id="id-input" name="author">
      <input class="c1" type="submit" value="Send">
    </form>
  </body>
</html>

CSS

.c1 {width:80%; line-height:1em; padding:1em;margin:1em 10%;}

it's absolutely not my attitude for PHP or MySQL however sorry for requesting the solution code directly.

regards

回答1:

I found the answer here http://jsfiddle.net/67XDq/7/

regards

HTML

<tr id="rq17">
<td class='qnum'>17.</td>
<td class='qtext'>Questions? <i>Maximum of 500 characters - <input style="color:red;font-size:12pt;font-style:italic;" readonly type="text" id='q17length' name="q17length" size="3" maxlength="3" value="500"> characters left</i><br/><textarea onKeyDown="textCounter(this,500);"
onKeyUp="textCounter(this,'q17length' ,500)" class="scanwid" name="q17" id="q17" rows="5" cols=""></textarea></td>
</tr>

JS

function textCounter(field,cnt, maxlimit) {         
    var cntfield = document.getElementById(cnt) 
     if (field.value.length > maxlimit) // if too long...trim it!
        field.value = field.value.substring(0, maxlimit);
        // otherwise, update 'characters left' counter
        else
        cntfield.value = maxlimit - field.value.length;
}