4

I have a textarea where users can input either English or Chinese, or both. maxLength="50" is fine for English but I hope to limit Chinese characters to only 20. If it's the case of a mixture it should be also limited to 20. Not sure how I can do that?

Alvin Mok
  • 323
  • 1
  • 14

4 Answers4

5

jQuery solution?

jQuery

$(function(){
    $("#textarea").on("keydown change", function(e){
        if (e.keyCode == 8)
            return;
        var x = $(this).val();
        if (x.match(/[\u3400-\u9FBF]/) && x.length >= 20) {
            e.preventDefault();
            $(this).val(x.substring(0,20));
        } else if (x.length >= 50){
            e.preventDefault();
            $(this).val(x.substring(0,50));
        }
    });
});

Or if you want to make it a jQuery method to make it easier to make multiple special inputs.

Extending that jQuery :D

$(function(){
    $.fn.extend({
        chiInput: function(chiLimit, engLimit){
            chiLimit = parseInt(chiLimit, 10) || 20;
            engLimit = parseInt(engLimit, 10) || 50;
            $(this).on("keydown change", function(e){
                if (e.keyCode == 8)
                    return;
                var x = this.value;
                if (x.match(/[\u3400-\u9FBF]/) && x.length >= chiLimit) {
                    e.preventDefault();
                    this.value = x.substring(0,chiLimit);
                } else if (x.length >= engLimit){
                    e.preventDefault();
                    this.value = x.substring(0,engLimit);
                }
            });
            return this;
        }
    });
});

HTML

<input class="chinese-input" type="text">
<textarea class="chinese-input"></textarea>

So you can do $(".chinese-input").chiInput(20,50) to initiate the function binding on multiple inputs. Yeah!

$(function(){
    $("#textarea").on("keydown change", function(e){
        var x = $(this).val();
        $("#length").text("length: "+x.length);
        if (e.keyCode == 8)
            return;
        if (x.match(/[\u3400-\u9FBF]/) && x.length >= 20) {
            e.preventDefault();
            $(this).val(x.substring(0,20));
        } else if (x.length >= 50){
            e.preventDefault();
            $(this).val(x.substring(0,50));
        }
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<textarea id="textarea" rows=1 cols=50></textarea>
<p id="length">length: </p>
<hr>
<p>You can copy this following Chinese to test: 這是一段中文文字。 (length: 9)</p>
Daniel Cheung
  • 4,779
  • 1
  • 30
  • 63
  • 1
    Thanks. jQuery seems more powerful? Am I correct to say that the above codes detect the language from the user's input rather than from the browser? So it's more accurate? – Alvin Mok Aug 31 '15 at 10:37
  • @AlvinMok That's correct, because detecting the language of the browser is totally not fair :) – Daniel Cheung Aug 31 '15 at 10:39
  • @AlvinMok But if you are not already using jQuery for your website, I suggest translating this to vanilla JS because you wouldn't want to load a 30kB library just for this occasion. – Daniel Cheung Aug 31 '15 at 10:43
  • @AlvinMok If you are testing, I've fixed a bug. I've deleted the second code – Daniel Cheung Aug 31 '15 at 10:51
  • Thanks. But I realise I can copy a long string of Chinese characters and paste it at the last key to trick the rules. Is there a way to prevent this? – Alvin Mok Aug 31 '15 at 10:57
  • Now with the updated codes, when I reached the limit, I cannot edit the text anymore. – Alvin Mok Aug 31 '15 at 11:00
  • @AlvinMok I've fixed it with the newest version. Now I'm trying to simplify it. – Daniel Cheung Aug 31 '15 at 11:02
  • @AlvinMok I've updated my answer to include a custom jQuery method :) See if it helps you. Remember, if you find my answer helpful, you can mark it as answer. – Daniel Cheung Aug 31 '15 at 11:12
  • Thanks Daniel. Strangely, the second method doesn't seem to work. The first method works fine, thanks again, but with a problem: I can paste a string of characters at the last key to exceed to the Chinese maxLength. What do you think? – Alvin Mok Aug 31 '15 at 11:27
  • @AlvinMok I've updated my answer. The new method will run the function when `keypress` and `change`. So pasting a string won't last long. Please try the snippet. – Daniel Cheung Aug 31 '15 at 11:46
  • You are right. Text is deleted once the area isn't selected. But I think I should warn the users. They may not check it. – Alvin Mok Aug 31 '15 at 11:53
  • @AlvinMok 加油! Good luck, fellow Chinese – Daniel Cheung Aug 31 '15 at 11:56
1

Use the window.navigator.language property, it contains the "language code" of the language currently used (http://www.metamodpro.com/browser-language-codes).

If you have this HTML :

<input id="myInput" type="text" maxlength="50"/>

Then you can do :

JS :

var myInput = document.querySelector('#myInput');
if(navigator.language === "zh") myInput.setAttribute('maxlength', 20); //zh is chinese, this code will set the maxlength to 20 ONLY for chinese language, others will have 50, like specified in the HTML.
Lauromine
  • 1,453
  • 9
  • 19
  • 1
    but what if i'm using a chinese browser but typing in english? would this prevent me from typing 50 characters? – Daniel Cheung Aug 31 '15 at 10:38
  • Yes, OP did not specify if it has to be browser-dependent or keyboard-dependent – Lauromine Aug 31 '15 at 10:40
  • 2
    OP did say "if it's a mixture". Do you reckon someone can have a mixed language browser language? – Daniel Cheung Aug 31 '15 at 10:41
  • Not sure if window.navigator.language or languages for interoperability. Looks like implementations were changing quite a lot in recent years: http://stackoverflow.com/questions/1043339/javascript-for-detecting-browser-language-preference – XLII Aug 31 '15 at 10:46
0

To check the current language you can:

  • determine it from the browser language
  • determine it from an option selected by the user

While the second option is a custom code and you need only to save the preference of the user in a variable, the first code can be accomplished with the following code:

// This to handle differences between browsers (userLanguage for old IE versions)
var language = window.navigator.userLanguage || window.navigator.language;

Now if you have the language simply define limit as follow:

var maxSize = 40;
if (language == 'ZH') {
   maxSize = 20;
}

... // Your checks here
Davide Lorenzo MARINO
  • 26,420
  • 4
  • 39
  • 56
0

You could detect the languages as follows:

var language = window.navigator.userLanguage || window.navigator.language;
alert(language); //works IE/SAFARI/CHROME/FF

// navigator.userLanguage for IE
//window.navigator.language for firefox/opera/safari

Some language code: 'it' = italy, 'en' = english

I also found a tool that could be helpful for you while detecting languages : franc

Suhail Gupta
  • 22,386
  • 64
  • 200
  • 328