Use jQuery to switch between left and right alignment, depending on the language

I have input and text fields that need to be switched between left justification and right justification (depending on the user's language, the direction will be different). How can I do this using jQuery?

+5
source share
6 answers

Here I completely reworked the Mohammad script, but it limited itself to its purpose: to scan if the first letter the user enters is Persian and changes the direction of the entries according to.

Here it is: jsfiddle.net/uPH7N/4

+1
source

key code , :

var str = $('#item').val();  //this is your text box
var firstChar = str.substr(0,1);
var characters = ['ا','ب','پ','ت','س','ج','چ','ح','خ','د','ذ','ر','ز','ژ','س','ش','ص','ض','ط','ظ','ع','غ','ف','ق','ک','گ','ل','م','ن','و','ه','ی'];
function checkPersian() {
    var result = false;
    for (i = 0 ; i<32 ; i++) {
        if (characters[i] == firstChar) {
            result = true;
        }
    }
    return result;
}
if (checkPersian()) {
    $('#item').css('direction','rtl');
} else {
    $('#item').css('direction','ltr');
}
+4

You can use the attribute dir="auto"in modern browsers: Live Demo

<input type="text" dir="auto"><br>

You can also do this using jQuery as follows: Live Demo

$('input, textarea').keyup(function() {
    $(this).val().charAt(0).charCodeAt(0) < 200 ? $(this).css('direction','ltr') : $(this).css('direction','rtl');
});
+2
source

Switch css elements with jquery (assuming the corresponding inputs / text fields have a class textdirectionBoxes):

$('.textdirectionBoxes').css('direction', 'rtl');

and

$('.textdirectionBoxes').css('direction', 'ltr');
0
source

What about

jQuery( document ).ready( function(){
    var language = navigator.userLanguage || navigator.language;
    if( jQuery.inArray( language, ['ar', 'he', 'ur'] ) != -1 )
        jQuery( 'input[type="text"], input[type="password"], textarea' ).css( 'direction', 'rtl' );
});

?

edit: few code bugs fixed

0
source
function isUnicode(str) {
    return (str.charCodeAt(str.length-1) > 255) ? true : false;
}

$('input[type=text]').each(function() {
    $(this).keyup(function(e) {
        $(this).css('direction',
            isUnicode($(this).val()) ? 'rtl' : 'ltr'
        );
    });
});
0
source

All Articles