What's the best way to place the text or operator from a button into an input field?

Hello, I am currently working on developing a calculator. However, I have encountered an issue where clicking on operator buttons such as +, -, /, *, and the dot button does not add them to my input field. Additionally, when these buttons are clicked, the entire value in the input tag gets erased. Can anyone provide guidance on how to resolve this issue? Any help would be greatly appreciated.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="calci.css">
</head>

<body>
    <p id="para"></p>
    <div class='main'>
        <div class="showText">
            <input class="input" type="number" id="input" disabled><br>
        </div>
        <div>
        <div class="buttons">
            <button type="button" id="block1">1</button>

            <button type="button" id="block2">2</button>

            <button type="button" id="block3">3</button>

            <button type="button" id="block4">4</button>

            <button type="button" id="block5">5</button>

            <button type="button" id="block6">6</button>

            <button type="button" id="block7">7</button>

            <button type="button" id="block8">8</button>

            <button type="button" id="block9">9</button>

            <button type="button" id="block0">0</button>

            <button type="button" id="dot" value=".">.</button>
        </div>
        <div class="operators" >
            <button class="add" id="plus" value="+">+</button>
            <button class="substract" id="minus" value="-">-</button>
            <button class="division" id="divide" value="/">/</button>
            <button class="multiply" id="multiply" value="*">*</button>
            <button id="ans">Answer</button>
            <button type="reset" id="clr">Reset</button>
            
            
        </div>
        </div>
    </div>
    <script src="calci.js"></script>
</body>

</html>

JavaScript starts here:

let input = document.querySelector('.input');
let button = document.querySelectorAll('button');

for(let btn of button){
    btn.addEventListener('click',()=>{
      if(input.value == ""){
        input.value = (btn.innerText);
      }
      else if(input.value != "" ){
        input.value += btn.innerText;
      }
    })
}

CSS starts here:

*{
    margin: 0;
    padding: 0;
}

body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main {
    text-align: center;
    margin-top: 2rem;
}
input{
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 10px;
}

Answer №1

When the input type is set to number, it is important to change it to text in order to accept special characters.

let input = document.querySelector('.input');
let button = document.querySelectorAll('button');

for(let btn of button){
    btn.addEventListener('click', ()=>{
        console.log(btn.textContent)
        input.value += btn.textContent;
    })
}
*{
    margin: 0;
    padding: 0;
}

body{
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
.main {
    text-align: center;
    margin-top: 2rem;
}
input{
    padding: 10px;
    margin-top: 10px;
    margin-bottom: 10px;
}
<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title></title>
    <meta name="description" content="">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="calci.css">
</head>

<body>
    <p id="para"></p>
    <div class='main'>
        <div class="showText">
            <input class="input" type="text" id="input" disabled><br>
        </div>
        <div>
        <div class="buttons">
            <button type="button" id="block1">1</button>

            <button type="button" id="block2">2</button>

            <button type="button" id="block3">3</button>

            <button type="button" id="block4">4</button>

            <button type="button" id="block5">5</button>

            <button type="button" id="block6">6</button>

            <button type="button" id="block7">7</button>

            <button type="button" id="block8">8</button>

            <button type="button" id="block9">9</button>

            <button type="button" id="block0">0</button>

            <button type="button" id="dot" value=".">.</button>
        </div>
        <div class="operators" >
            <button class="add" id="plus" value="+">+</button>
            <button class="substract" id="minus" value="-">-</button>
            <button class="division" id="divide" value="/">/</button>
            <button class="multiply" id="multiply" value="*">*</button>
            <button id="ans">Answer</button>
            <button type="reset" id="clr">Reset</button>
            
            
        </div>
        </div>
    </div>
    <script src="calci.js"></script>
</body>

</html>

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

Angular 4 is unable to attach to 'formGroup' as it is not recognized as a valid property of 'form'

As a beginner with Angular 4, I decided to explore model driven forms in Angular 4. However, I keep encountering this frustrating error. Template parse errors: Can't bind to 'formGroup' since it isn't a known property of 'form ...

Tips for determining whether a value is present in an array or not

I'm trying to prevent duplicate values from being pushed into the selectedOwners array. In the code snippet below, the user selects an owner, and if that owner already exists in the selectedOwners array, I do not want to push it again. How can I imple ...

Ways to showcase title using ng-repeat

<input type="text" ng-model= "name" title="{{name}}">//this title displays the name that is contained in ng-model Similarly... <select title ="{{item.actionId}}" ng-model="item.actionId"> <option ng-repeat="action in actionList" value="{{ ...

Accessing data in JSON format from a URL

I'm working on a website that analyzes data from the game Overwatch. There's this link () that, when visited, displays text in JSON format. Is there a way to use JavaScript to read this data and display it nicely within a <p> tag on my si ...

Prepare the writing area for input

My inputs have validation indicators, such as a green tick or red cross, placed at the very right of the input (inside the input). Is there a way to specify the writing space inside an input without restricting the number of characters that can be enter ...

What is the best way to alternate between two CSS stylesheets when using jQuery-UI?

Just getting started with jQuery and javascript and decided to test out 2 different jQuery-ui stylesheets in a simple .html file. The goal is to have the example dialog open with the "flick" stylesheet and the datepicker within the dialog open with the "u ...

The issue of why padding left is not functioning correctly in Bootstrap version 5.3.1

</head> <body> <header class="bg-info "> <div class="container"> <div class="row text-white"> <div class="col-md-6 p-3 pl-6 "> ...

Infinite rendering caused by React custom hook

I developed a custom hook that retrieves data from a News API and provides handling for loading, errors, and data (similar to Apollo Client). The issue I'm facing is that the hook seems to trigger infinitely, even when the items in the dependency arra ...

Why does my array seem to update only once in the view?

I am currently working on a project that aims to visually represent sorting algorithms, but I have encountered an issue. In order to effectively visualize the sorting process of an algorithm, it is crucial to display every change in the array as the proc ...

Using Javascript to define cookie values

I'm attempting to use JavaScript to set a cookie that will instruct Google Translate to select the language for the page. I've experimented with setting the cookie based on my browser's cookie selection of a language. <script> $(doc ...

The div is repositioned without the use of padding or margin properties

I am facing an issue with my Next.JS application where a div is not aligning properly at the top of the page. Despite setting padding and margin to 0 for body, HTML, and the div itself, it seems to be slightly off. I have checked all components thoroughly ...

Protractor's count() function fails to execute properly when called outside of a promise loop

var alerts = element.all(by.xpath("//div[@class='notification-content']")); alerts.count().then(function (val) { console.log(val); }); let compareValue = val; Is there a way to access the 'value' outside of the promise l ...

How should script files be imported correctly in Next Js?

I've been struggling to import JS files in a template of Bootstrap. The CSS files are imported properly, but I'm facing issues with JS imports. I learned that in Next.js, you can import them using the useEffect hook. However, even after implement ...

Creating an object and setting its prototype afterwards

While exploring examples and questions online about prototypal inheritance, I noticed that most of them involve assigning prototypes to constructor functions. One common pattern is shown in the code snippet below: Object.beget = function (o) { var F = ...

When the onInput event is triggered, React renders components and console.log() displays different values

When I type in the input field, it triggers the onInputChange() function. This function updates the state of inputValue, and then calls the getValue() function which retrieves the current state of inputValue and logs it to the console. However, the value d ...

Extracting URL from HTML automatically

I'm in the tedious process of copying multiple URLs from a website, which involves clicking on numerous links and then pasting the URL (along with other information) into an Excel file. This method is incredibly time-consuming, especially since I have ...

Iteratively modify each essential attribute of a JSON object

In my data set, I have moisture levels recorded at various timestamps in a JSON object: { "values": { "21-Aug-2020 20:28:06:611591": "58.59", "21-Aug-2020 20:28:09:615714": "71.42", "21-A ...

Guide on how to trigger a pop-up modal to open a new webpage by clicking on a hyperlink

I have a page called one.html that has a link on it <a href="#">Click to open second page<a/> When this link is clicked, I would like for second.html to open in a popup modal. The second page contains a basic table that I want to di ...

"Receiving the error message 'Object is not a function' occurs when attempting to pass a Node.js HTTP server object to Socket.IO

A few months back, everything was working fine when I set up an HTTPS server. Recently, I revisited the application and decided to switch to HTTP (though this change may not be directly related). In my code snippet below from 'init.js', I create ...

Can CSS modules be used in conjunction with outside libraries?

I've incorporated a Slider library () into my React project. While regular CSS allows me to style the slider properly, I am facing issues when using css modules. The tsx file looks like this: import styles from './styles.module.css'; . . . ...