"Enhance your website with a backspace button using jquery - here's

Recently, I delved into the world of jQuery and decided to test my skills by creating a jQuery calculator. Everything worked perfectly except for the backspace button.

This is what I tried:

if (value === backspace) {
$(input).val($(input).val().substring(0, $(input).val().length - 1));

}

Unfortunately, it didn't work as expected.

Here is the HTML code:

<!DOCTYPE html>
<html>
    <head>
        <title>Calculator</title>
        <link rel="stylesheet" type="text/css" href="calculator.css">
    </head>
    <body>
        <div class="container">
            <input type="text" name="">
            <div class="btns">
                <input type="submit" name="btn1" value="1">
                <input type="submit" name="btn2" value="2">
                <input type="submit" name="btn3" value="3">
                <input type="submit" name="btn4" value="4">
                <input type="submit" name="btn5" value="5">
                <input type="submit" name="btn6" value="6">
                <input type="submit" name="btn7" value="7">
                <input type="submit" name="btn8" value="8">
                <input type="submit" name="btn9" value="9">
                <input type="submit" name="btn0" value="0">
                <input type="submit" name="plus" value="+">
                <input type="submit" name="minus" value="-">
                <input type="submit" name="mulpy" value="*">
                <input type="submit" name="div" value="/">
                <input type="submit" name="mod" value="%">
                <input type="submit" name="div" value="=">
                <input type="submit" name="reset" value="reset">
                <input type="submit" name="back" value="&larr;">
            </div>
        </div>
        <script
        src="https://code.jquery.com/jquery-3.4.1.min.js"
        integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
        crossorigin="anonymous"></script>
        <script type="text/javascript" src="calculator.js"></script>
    </body>
</html>

Here is the corresponding CSS:

body {
margin: 0;
padding: 0;
box-sizing: border-box;
display: flex;
justify-content: center;
align-items: center;
background: #45D196;
background: -moz-linear-gradient(left, #45D196 0%, #1C6EA4 44%, #A6C55F 100%);
background: -webkit-linear-gradient(left, #45D196 0%, #1C6EA4 44%, #A6C55F 100%);
background: linear-gradient(to right, #45D196 0%, #1C6EA4 44%, #A6C55F 100%);
}

.container {
width: 300px;
margin-top: 100px;
border-radius: 5px;
-webkit-box-shadow: 5px 5px 15px 5px rgba(0,0,0,0.25); 
box-shadow: 5px 5px 15px 5px rgba(0,0,0,0.25);
}

.btns,
.container {
    display: flex;
    flex-wrap: wrap;
}


input[type = "submit"] {
cursor: pointer;
width: 100px;
height: 50px;

}

input[type = "text"] {
width: 100%;
height: 50px;
font-size: 30px;
outline: none;
border-top-right-radius: 5px;
border-top-left-radius: 5px;
border: 1px solid #45D196;
}

Lastly, here is the JavaScript snippet:



$( document ).ready(function() {


let input= $('input[type="text"]');

$(".btns").click(function(e) {
let $current_val = $(input).val();
let value = $(e.target).val();
$(input).val($current_val + value);
let backspace = $("input:last-child").val();

if (value === "reset") {
$(input).val("");

}

if (value === "=") {
let answer = eval($current_val);
$(input).val("");
$(input).val(answer);   
}

if (value === backspace) {
$(input).val($(input).val().substring(0, $(input).val().length - 1));

}

});

});

Thank you in advance!

Answer №1

Your code implementation for adding characters to the display is executing before handling backspace input, resulting in redundant addition and removal of backspace character on the display. To resolve this issue, you can modify the code snippet from

$(input).val($(input).val().substring(0, $(input).val().length - 1))
to
$(input).val($(input).val().substring(0, $(input).val().length - 2))
. However, a better approach would be to refactor your code structure. Consider replacing multiple if-statements with an if-else chain that handles special actions with a default action at the end. You could structure it like this:

let value = $(e.target).val();
let backspace = $("input:last-child").val();
let $current_val = $(input).val();

if (value === "reset") {
    $(input).val("");
} else if (value === "=") {
    let answer = eval($current_val);
    $(input).val("");
    $(input).val(answer);
} else if (value === backspace) {
    $(input).val($(input).val().substring(0, $(input).val().length - 1));
} else {
    $(input).val($current_val + value);
}

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

Redux: The action was effectively triggered, but the state remained unformed

I'm currently working on a project to familiarize myself with Redux. I am using the Redux DevTools to monitor my two states: lists and todos. However, I am running into an issue where only todos are being displayed, despite trying various troubleshoot ...

Exploring etoro data through python web scraping

Attempting to automate the process of logging into my etoro account and extracting data from my portfolio using Selenium. Currently working on Google Colab, here is what I have so far: from selenium import webdriver options = webdriver.ChromeOptions() opt ...

Having trouble updating a MongoDB array through a RESTful API PUT request

I'm brand new to the MEAN stack and recently completed a tutorial. I've been working on enhancing a simple application that utilizes a RESTful API to update a MongoDB. Currently, I'm using a PUT statement to modify specific parts of my colle ...

Deactivate the submit button when the form is not valid in angularjs

I am currently facing a challenge with my form that contains multiple input fields. To simplify, let's consider an example with just two inputs below. My goal is to have the submit button disabled until all required inputs are filled out. Here is wha ...

AJAX loading footer content before images are fully loaded

I am a beginner when it comes to ajax and I'm facing an issue where the footer loads before the images, causing the images to overlap the footer. The problem is illustrated in the image below. <!doctype html> <html lang="en"> <head ...

The MTM test runner is failing to identify AJAX callbacks

During my manual testing, I encountered an issue where the recorded test would get stuck after a button click and not proceed to the next page, causing the test to fail. This problem also occurred in CUIT, but I was able to resolve it using Ross McNab&apos ...

How can I integrate the jQuery Plugin Mapael with Angular 5?

While exploring various methods that tackled the issue of integrating jQuery Plugins, I decided to start with the fundamentals. To begin with, I installed the jQuery plugin: npm i jquery Next, I included the TypeScript definition: npm install -d @types ...

Sending HTML form information to PHP isDomainAvailable function

I am in the process of creating a website monitoring system. I have constructed an HTML form to collect data and send it to a PHP script, but I am encountering some difficulties. The HTML form is a standard one that uses the GET method. Here is my PHP cod ...

What is the best way to reset Owl Carousel following an ajax request?

I am attempting to reinitialize the owl carousel following a successful ajax call. The ajax call will update the data while retaining the same view. I am encountering an issue where the carousel structure in the view does not reinitialize, and I am unsure ...

Ways to retrieve a list of identifiers from arrays at both initial and subsequent levels

I'm currently dealing with a JSON/JavaScript structure that looks like this: { "comments": [ { "id": 1, "content": "lorem ipsum", "answers": [] }, { "id" ...

Struggling with getting the navigation bar to show up in a row instead of stacking

Hey there, I need some help with the layout of my page. Here's the link to the page I'm currently working on: At the moment, the list is showing up vertically instead of horizontally. CSS: li { display:inline; list-style-type:none; ...

What are the advantages of combining a library (using Rollup or Webpack) instead of simply transpiling it with Babel?

When developing a library in JavaScript, what are the benefits of using tools like Rollup or Webpack for bundling rather than just transpiling with Babel? One potential advantage could be that by bundling, you ensure that your dependencies are packaged eff ...

A Step-by-Step Guide on Sending Response to ajaxError Callback in Perl

When working with JavaScript, I have a method of capturing errors that looks like this: $(document).ajaxError(function(event, jqxhr, settings, thrownError) { handleError(MSG_SAVE_ERROR); }); Now, my question is how can I retrieve an error message fro ...

Submitting with enter key on typeahead suggestions

Seeking guidance on Bootstrap typeahead: how can I configure it to submit the entered text upon pressing the enter key? Specifically, if I type "hello" in the typeahead input and hit enter, how can I submit "hello"? I've successfully disabled the aut ...

Tips for aligning pagination block at the center using react-bootstrap

Currently, I have implemented a custom pagination system for a small web application that I am developing using react-bootstrap. I have successfully integrated and set up the pagination functionality. As someone who is still new to react and bootstrap, wit ...

jQuery's class selector does not work for dynamically added labels

The HTML code appears to be: <label for="13"> <input id="13" value="13" type="radio" name="choice">S1&nbsp;&nbsp;&nbsp;S1&nbsp;&nbsp;&nbsp; </label> <label for="14"> <input id="14" value="14" typ ...

When I separate the div into its own line in the HTML/CSS code, the behavior changes significantly

I'm encountering an issue with my HTML/CSS structure: .im-wrapper { width: 100%; height: 100%; position: fixed; overflow: hidden auto; top: 0; left: 0; } .im-backdrop { background-color: var(--darkblack); opacity: 80%; width: 1 ...

Cannot find WoopraTracker within the custom event data

I am currently working on implementing Woopra custom event data upon page load by following their guidelines. I have attempted to push events when the page is ready, however, it keeps returning an error that woopratracker is not defined. Strangely, when ...

Finding the file in a separate directory within the src path

In my projects directory, I have a folder named projects which contains both a game folder and an engine folder. Inside the engine folder, there is an engine.js file. My issue is that I want to access this engine.js file from my game.html file located in a ...

jquery method to make entire navigation bar clickable

I have a single menu bar. I recently discovered an interesting way to make the entire menu bar area clickable using jQuery. Design code snippet: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MenuControl.ascx.cs" Inherits="MenuControl"%> ...