Basic JavaScript string calculator

I'm in the process of creating a basic JavaScript calculator that prompts the user to input their name and then displays a number based on the input. Each letter in the string will correspond to a value, such as a=1 and b=2. For example, if the user enters "acb" into the input, it should display abc=1+2+3 =6. Thanks!

<input type="text" id="myText" value="">

<button onclick="myFunction()">Try it</button>

<p id="calc"></p>

 <script>
function myFunction() {
   var x = document.getElementById("myText").value;
   document.getElementById("calc").innerHTML = x;
}
</script>

Answer №1

Give this method a try - it utilizes a basic code where a is 1 and z is 26. Any special characters or numbers entered will be considered as 0. This solution is effective for both uppercase and lowercase letters.

function generateValue() {
   var input = document.getElementById("textInput").value;
 var sum = 0;
 for (var j = 0; j < input.length; j++) {
   var value = input.toLowerCase().charCodeAt(j) - 96;
 if ((value > 0) & (value < 27)) {
   sum = sum + value;
 }
 }
   document.getElementById("result").innerHTML = sum;
}
<input type="text" id="textInput" value="">
<button onclick="generateValue()">Calculate</button>

<p id="result"></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using a nested loop in Javascript to fetch JSON data

My goal is to display Categories and their corresponding subcategories in a specific order. However, my current method of using loops within loops is not producing the desired outcome: Category(Mobile) Category(Laptop) Subcategory(Iphone4) Subcategory(Iph ...

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

What is the process for setting up URL parameters in Express JS?

I am working on creating an URL that can accept a query after the "?" operator. The desired format for the URL is "/search?q=". I am wondering how I can achieve this in Express JS, and also how I can integrate the "&" operator into it. ...

Using local storage with github sites can lead to some unexpected and peculiar behavior

Currently, I am working on a simple clicker game using HTML and JavaScript. To store the variables money and taxCollecters, I have implemented local storage. However, I am encountering strange issues when trying to use the save and load buttons on the Gi ...

Caution: PHP's move_uploaded_file() function is unable to successfully relocate the audio file

I've implemented a straightforward Record Wave script using Recorder.js Encountering an Issue Recording works fine Playback of my recording is successful Downloading the recorded file from blob works smoothly The problem arises when trying to uploa ...

Employing ngModel within an (click) event in Angular 4

I have this html code snippet: <div class="workflow-row"> <input type="checkbox" id="new-workflow" [(ngModel)]="new_checkbox"> <label>New Workflow</label> <input type="text" *ngIf="new_checkbox" placeholder="Enter ...

Saving data in multiple collections using MongoDB and Node.js: A comprehensive guide

In a recent project of mine, I have implemented a combination of nodeJS and mongodb. My main goal is to store data in multiple collections using just one save button. Below is the code snippet that I am currently working with: var lastInsertId; loginDat ...

Utilize Vue.js functions within data through the Vue.js context

I'm trying to incorporate a function as a data property. While it works for the 'works' data property, I need access to the this context within the function in order to calculate values from the shoppingCart property. Is there a way to achie ...

Adjust the text color of a particular word as you type using the contenteditable property set to "true"

I'm attempting to jazz things up a bit. For instance, I have a div that is set as contenteditable="true". What I want to achieve is changing the color of a specific word I type while writing. In this case, let's say the word "typing" sh ...

Adding a new column to a table that includes a span element within the td element

I am attempting to add a table column to a table row using the code below: var row2 = $("<tr class='header' />").attr("id", "SiteRow"); row2.append($("<td id='FirstRowSite'><span><img id='Plus' s ...

Error in form action when generated through an ajax partial in Ruby

I am facing an issue with a form that is loaded via an ajax partial. The problem arises when the form loads through ajax as it targets the wrong controller/url instead of the intended one. Despite my efforts to set the target controller correctly, it keeps ...

Converting a text area into a file and saving it as a draft in the cloud with the

Can content from a text area be converted into a file of any chosen format and saved in the cloud? Additionally, should every modification made in the text area automatically update the corresponding file stored in the cloud? ...

When attempting to make a GET request, Express/Mongoose is returning a null array

I am having trouble retrieving the list of books from my database. Even though I have successfully inserted the data into Mongoose Compass, when I try to fetch it, all I get is an empty array. //Model File import mongoose from "mongoose"; cons ...

Unable to retrieve JSON data for the JavaScript object

I have been working on creating a JS object in the following manner var eleDetailsTop = new Array(); var j = 0; var id = "ele"+j; eleDetailsTop[id] = {id: id, size : "40%", sizeLabel : 12, type : "image", title : "Image& ...

Issue encountered in Next.JS when attempting to validate for the presence of 'window == undefined': Hydration process failed due to inconsistencies between the initial UI and the server-rendered

I encountered an issue that says: Hydration failed because the initial UI does not match what was rendered on the server. My code involves getServerSideProps and includes a check within the page to determine if it is running in the browser (window==&apo ...

Utilizing various layouts in ASP.NET MVC with AngularJS

I am setting up two different layouts, one for visitors and one for management. Routes: app.config(['$routeProvider', function ( $routeProvider) { $routeProvider .when('/', { templateUrl: 'Home ...

When you hover over an image, its opacity will change and text will overlay

I am looking for a way to decrease the opacity and overlay text on a thumbnail image when it is hovered over. I have considered a few methods, but I am concerned that they may not be efficient or elegant. Creating a duplicated image in Photoshop with the ...

Utilizing jQuery AJAX to Send an HTML Array to PHP

In my current HTML forms and jQuery AJAX workflow within the Codeigniter Framework, I've encountered a common issue that has yet to be resolved to suit my specific requirements. Here's the situation: HTML - The form includes an array named addre ...

Deactivate the button in the final <td> of a table generated using a loop

I have three different components [Button, AppTable, Contact]. The button component is called with a v-for loop to iterate through other items. I am trying to disable the button within the last item when there is only one generated. Below is the code for ...

How can I make Material UI's grid spacing function properly in React?

I've been utilizing Material UI's Grid for my layout design. While the columns and rows are functioning properly, I've encountered an issue with the spacing attribute not working as expected. To import Grid, I have used the following code: ...