Need help fixing my issue with the try-catch functionality in my calculator program

Can someone assist me with my Vue.js calculator issue? I am facing a problem where the output gets added to the expression after using try and catch. How can I ensure that both ERR and the output are displayed in the {{output}} section? Any help would be appreciated!

https://i.sstatic.net/7dORR.png

https://i.sstatic.net/BcrnG.png

Here is the specific part causing trouble:

                else if (but == "=") {
                    try {
                        eval(this.expression)
                        // this.output = eval(this.expression)
                    } catch (error) {
                            this.output = "ERR"
                            // throw e;
                        }
                }

For reference, here is the full code:

<html>

<head>
    <title>calculator</title>

    <!-- Vue 3: development -->
    <script src="https://unpkg.com/vue@next"></script>

    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.0/css/all.css"
        integrity="sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ"
        crossorigin="anonymous">
    <link rel="stylesheet"
        href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
        integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
        crossorigin="anonymous">
    <meta charset="UTF-8">
</head>

<body>
    <div id="app" class="container" style="width: 400px;">

        <div class="row border m-3 text-right" style='height:100px;'>
            <div class="col">
                {{expression}}
                {{output}}
            </div>
        </div>
        <div class="row text-center">
            <div class="col">
                <template v-for="i in button.length">
                    <button id="button[i-1]"class="btn btn-light m-2" style="width:50px" @click="action(button[i-1])">
                        {{button[i-1]}}
                    </button>
                    <br v-if=" i % 4 == 0">
                </template>
            </div>
        </div>

            

        </div>


    </div>

</body>

<script>
    Vue.createApp({
        data() {
            return {
                expression: "",
                output: "",
                button: ["1","2","3","AC", "4", "5", "6", "+", "7", "8", "9", "-", "0", ".", "="]
            };
        },
        methods: {
            action(but) {
                console.log(but)
                if (this.expression == "" && (but ==  "+" || but =="-")){
                    this.expression = "0" + but
                }
                else if (but == "=") {
                    try {
                        eval(this.expression)
                        // this.output = eval(this.expression)
                    } catch (error) {
                            this.output = "ERR"
                            // throw e;
                        }
                }
                else{
                    this.expression = this.expression + but
                }
                // if =
                if (but == "AC") {
                    this.expression = ""
                    this.output = ""
                }
            }
        },
        computed: {
        }
    }).mount('#app')

</script>
</body>

</html>

Answer №1

After careful observation, I realized my mistake - it was simply missing a <br>. :( Oh my goodness, I wasted so much time debugging

                {{expression}}
                <br>
                {{output}}

https://i.sstatic.net/FRLR6.png

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

Sending data between PHP and JavaScript using Ajax communication

I am currently working on a PHP page that involves variables and radio buttons. When a user clicks on a radio button, it triggers a JavaScript function to calculate the price of the selected item by passing some variables. Here's how I have implemente ...

What could be causing my React button to stop functioning as a link to an external website when using anchor tags?

I recently created some buttons for my website using React. Initially, everything was working perfectly with the buttons, but suddenly they stopped functioning. Strangely, I didn't make any alterations to the code and I'm puzzled as to why they a ...

Tips for identifying whether a form contains any empty fields and, if it does, directing focus to an anchor element

Is it possible to determine if a specific form contains any input fields? What about if it doesn't have any input fields? Additional Query: Also, how can I ensure that the focus is returned to a button when the page loads if the specified condition ...

Ways to dynamically fetch data by merging the response outcome with a dynamic parameter from the route in Vue.js

For the first time, I have been tasked with dynamically retrieving object parameters from the URL parameter. I am aware that I can use this.$route.params.[somelink-parameter] to obtain the URL parameter, and I understand how to retrieve and store the respo ...

Using JQuery to create a button inside a Modal dialog box

My goal is to select a row within a Table that is located inside a Modal window, and then have a button ('newBtn') within that Modal window trigger a post request to the server with the selected id of the row. However, the issue I am encountering ...

Is there a way to make my HTML file search beyond its current directory?

My HTML file seems to be having trouble searching in a different folder for the CSS file that I've linked. How can I make it search in the correct folder? I have my HTML file in a directory named INDEX and the CSS file in another directory named STYL ...

Safari is capable of rendering Jquery, whereas Chrome seems to have trouble

The code I am using renders perfectly in Safari but not in Chrome. Despite checking the console in Chrome, no errors are showing up. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <script src="ht ...

Using Tailwind @apply within an Angular application's CSS file

I've noticed a yellow line appearing under the @apply in my CSS files, even though the styles are being applied correctly to the HTML components. This seems to be happening in every CSS file I use. Can anyone shed light on this issue? Removing these ...

The jQuery extension for XDomainRequest in the $.ajax function called onprogress is

Summary: I am trying to make this compatible with this: Detailed Explanation: My goal is to develop a jQuery extension that introduces a progress method to the $.ajax object and works seamlessly with IE8 & IE9's XDomainRequest object. Currently, I ...

"The boundary of suspense was updated before completing hydration." This error occurs when utilizing suspense and dynamic import within Next.js

I am currently working on lazy loading a list of data using suspense and dynamic import in Nextjs. However, I encountered the following error: Error: This Suspense boundary received an update before it finished hydrating. This caused the boundary to switch ...

Strategies for halting the return of a JavaScript function until all AJAX requests have been completed

function processData(data) { //perform some data processing return data; } function test() { $.ajax({ 'url': api1, 'data': { 'use': "200" }, 'dataType': ' ...

Which programming language or technology utilizes the syntax <%VARIABLE%> and in what context is it employed?

First things first, I want to clarify that I'm not a developer, so this might be a simple question. Despite my research indicating that ASP typically uses this syntax, it's important to note that it is not the case here. I am currently delving i ...

Issue with vertical alignment in form input text area not functioning properly

Need some help aligning inputted text with the top of a textarea on an HTML form. I've scoured forums for solutions, but no luck so far. I attempted using: textarea{ vertical-align:top;} and input["textarea"]{ vertical-align:top;} Tried adding ...

When compiling, VUE fails to load page content

I am facing an issue with my VUE program that works perfectly locally but fails to work after compiling. The main concept is to load content from other files within the initial VUE App.vue file, specifically the Home.vue file App.vue <template> & ...

Issue with Discord.js (14.1) - Message Handling Unresponsive

After developing a sizable Discord Bot in Python, I decided to expand my skills and start learning JS. Despite thoroughly studying the documentation and comparing with my original Python Bot regarding intents, I am facing difficulties getting the message ...

Disable the ability to select all checkboxes in the Quasar Table component

Currently working with Quasar and I have implemented a table with multiple selections just like the image below: https://i.sstatic.net/fEoRT.png I am facing an issue where I cannot figure out how to hide the checkbox in the header that selects all option ...

Remove the div of the previous selection in jQuery and add the current selection by appending it, ensuring only one selection per row is allowed when

Here is a code snippet that includes buttons appending selections to the "cart" div upon clicking. The first script ensures only one selection per row when multiple buttons in the same row are clicked. In the second script, selections are appended to the ...

Perform CSS transitions simultaneously

Hey there! I'm currently working on a button that includes a Font Awesome icon at the end of it. To display the icon, I'm using the :after pseudo-element on the button, which is working fine so far. The issue I'm facing is with the CSS tran ...

Dealing with TypeScript errors TS2082 and TS2087 when trying to assign an Away3D canvas to a variable

As a beginner with TypeScript, I am in the process of creating an Away3D scene where a canvas element is dynamically generated and needs to be appended to a container. Although the code functions correctly, I am encountering the following compilation erro ...

Having trouble with sending information to the PHP server, unable to determine the root cause

Can someone help me figure out why the data from a form being sent to a php script for sending an email isn't working correctly? It's part of a template code but I suspect there might be an error. Specifically, I believe the {'userName' ...