Javascript Laravel | 631 Views

Auto-Translate English Form Inputs to Nepali Using JavaScript

's Gravatar
Feb 16, 2023

To automatically change English values to Nepali values in a Laravel 8 form, you can use JavaScript to detect when a value is entered into an input field, and then automatically convert the value to its Nepali equivalent.

Here’s an example code to achieve this:

  1. First, add a “data-convert” attribute to the input fields that you want to automatically convert to Nepali values. This attribute will be used to detect which fields need to be converted. For example:
<input type="text" name="name" data-convert>
  1. Next, add the following JavaScript code to the end of your form view. This code will listen for changes to the input fields with the “data-convert” attribute, and automatically convert any English characters to their Nepali equivalents using a mapping of English to Nepali characters.
<script>
  var englishToNepali = {
    'a': 'अ',
    'b': 'ब',
    'c': 'क',
    'd': 'ड',
    'e': 'इ',
    'f': 'फ',
    'g': 'ग',
    'h': 'ह',
    'i': 'ई',
    'j': 'ज',
    'k': 'क',
    'l': 'ल',
    'm': 'म',
    'n': 'न',
    'o': 'ओ',
    'p': 'प',
    'q': 'कु',
    'r': 'र',
    's': 'स',
    't': 'ट',
    'u': 'उ',
    'v': 'भ',
    'w': 'व',
    'x': 'एक्स',
    'y': 'वाई',
    'z': 'जेड'
  };

  $('input[data-convert]').on('input', function() {
    var originalValue = $(this).val();
    var newValue = '';

    for (var i = 0; i < originalValue.length; i++) {
      var character = originalValue.charAt(i).toLowerCase();
      if (englishToNepali[character]) {
        newValue += englishToNepali[character];
      } else {
        newValue += originalValue.charAt(i);
      }
    }

    $(this).val(newValue);
  });
</script>

In this example, the englishToNepali object contains a mapping of English characters to their Nepali equivalents. The $('input[data-convert]').on('input', ...) code listens for changes to the input fields with the “data-convert” attribute, and uses a loop to iterate through each character in the input value. If the character is an English character that has a Nepali equivalent in the englishToNepali object, the code replaces the character with its Nepali equivalent. Finally, the code sets the input field’s value to the new converted value.

Note that this code only works for simple conversions of English characters to their Nepali equivalents. It may not work correctly for complex words or phrases. Additionally, this code assumes that you are using the Devanagari script to represent Nepali characters, which may require additional font and language support in the user’s browser.