Having difficulty getting the sign operator to show up in a text field

Whenever the ADD div is clicked, "+" should be displayed on the textbox. The same goes for SUBTRACT, MULTIPLY, and DIVIDE. However, I am struggling to make the operators show on the textbox. Here is what I have managed to come up with so far.

    <!DOCTYPE html>
    <html>
    <body>

    <div class="leftDiv">
    <div id="colorblock">
    <div id = "add" class = "blocks" onclick="displayOptr()">ADD</div>
    <div id = "subtract" class = "blocks">SUBTRACT</div>
    <div id = "multiply" class = "blocks">MULTIPLY</div>
    <div id = "divide" class = "blocks">DIVIDE</div>
    </div>
    </div>
    <input type = "text" size="1" id = "operator">


    <script>
    function displayOptr() {
        var optrArr =["+","-","*","/"];
        for (var i = 0; i < optrArr.length; i++){
        if (i==0){
            document.getElementById("operator").value = "+";
            } else if (i==1){
            document.getElementById("operator").value = "-";
            } else if (i==2){
            document.getElementById("operator").value = "*";
            } else if (i==3){
            document.getElementById("operator").value = "/";    
        }
        

    }
    </script>

    </body>
    </html>

Answer №1

Your current issue stems from a missing closing curly brace in your if statement, causing an error that is halting the execution of your code.

Once you rectify this, your code proceeds to loop through an array and assigns one symbol to the textbox on each iteration. However, it then replaces that symbol in the next iteration, resulting in only having "/" displayed in the textbox when the loop finishes.

A simpler approach would be to directly pass the desired symbol as an argument to the function.

In addition, avoid setting event handlers as HTML attributes (e.g., onclick, onmouseover) as this outdated practice leads to messy "spaghetti code", makes code unreadable, lacks scalability, introduces global functions altering the 'this' binding, and deviates from W3C Standards for Event registration. Opt for using JavaScript's addEventListener() method for event binding instead.

Here's a revised version incorporating these changes:

<!DOCTYPE html>
    <html>
    <body>

    <div class="leftDiv">
    <div id="colorblock">
    <div id = "add" class = "blocks" onclick="displayOptr()">ADD</div>
    <div id = "subtract" class = "blocks">SUBTRACT</div>
    <div id = "multiply" class = "blocks">MULTIPLY</div>
    <div id = "divide" class = "blocks">DIVIDE</div>
    </div>
    </div>
    <input type = "text" size="1" id = "operator">


    <script>

    // Get references to the elements you'll need:
    var a = document.getElementById("add");
    var s = document.getElementById("subtract");
    var m = document.getElementById("multiply");
    var d = document.getElementById("divide"); 
    var output = document.getElementById("operator");

    // Set up click event handlers that each call the same function but pass it 
    // a different value.
    a.addEventListener("click", function(){ displayOptr("+") });
    s.addEventListener("click", function(){ displayOptr("-") });
    m.addEventListener("click", function(){ displayOptr("*") });
    d.addEventListener("click", function(){ displayOptr("/") });    

    function displayOptr(input) {
      // Just take the input and display in the textbox
      output.value = input;       
    }
    </script>

    </body>
    </html>

Answer №2

Since the loop runs 4 times, it will consistently display the symbol /. Give this a try:

<!DOCTYPE html>
<html>
  <body>
    <div class="leftDiv">
      <div id="colorblock">
        <div id = "add" class = "blocks" onclick="displayOptr('+')">ADD</div>
        <div id = "subtract" class = "blocks" onclick="displayOptr('-')">SUBTRACT</div>
        <div id = "multiply" class = "blocks" onclick="displayOptr('*')">MULTIPLY</div>
        <div id = "divide" class = "blocks" onclick="displayOptr('/')">DIVIDE</div>
      </div>
    </div>
    <input type = "text" size="1" id = "operator">
    <script>
      function displayOptr(symbol) {
          document.getElementById("operator").value = symbol;
      }
    </script>
  </body>
</html>

Answer №3

I have the impression that you might be making things more complex than necessary.

My recommendation would be to adjust your code to resemble the following:

<div class="leftDiv">
            <div id="colorblock">
                <div data-operator="+" class="blocks">ADD</div>
                <div data-operator="-" class="blocks">SUBTRACT</div>
                <div data-operator="*" class="blocks">MULTIPLY</div>
                <div data-operator="/" class="blocks">DIVIDE</div>
            </div>
        </div>
<input type="text" size="1" id ="operator" placeholder="" />

Please note that the data-operator attribute on the div elements is utilized in the script below:

var operatorInput = document.getElementById("operator") // reference to input field
var buttonList = document.querySelectorAll('.blocks') // array of all elements with blocks class

for(var i = 0; i < buttonList.length; i++){ // iterate through selected elements
    buttonList[i].addEventListener("click", function(e){ // attach a function to each element
        operatorInput.value = e.target.getAttribute("data-operator") // set input field value based on data-operator attribute
  })
}

This method allows for programmatically selecting and looping through all buttons to attach event-listeners for click events.

When a button is clicked, the function triggers an event (represented by e), which references the clicked button. The clicked button, accessed via event.target, contains the data-operator attribute used to display the desired symbol in the input field.

If you have any further inquiries, do not hesitate to ask.

You can find a functional example of this code in action at https://jsfiddle.net/66gu0zur/

Answer №4

If you need to show a different symbol based on the selected operation, you can use this solution:

<!DOCTYPE html>
<html>
<body>

<div class="leftDiv">
<div id="colorblock">
<div id = "add" class = "blocks" onclick="displayOptr(this);">ADD</div>
<div id = "subtract" class = "blocks" onclick="displayOptr(this);">SUBTRACT</div>
<div id = "multiply" class = "blocks" onclick="displayOptr(this);">MULTIPLY</div>
<div id = "divide" class = "blocks" onclick="displayOptr(this);">DIVIDE</div>
</div>
</div>
<input type = "text" size="1" id = "operator">


<script>
function displayOptr(that) {
    var val = that.id;
      if (val == "add"){
        document.getElementById("operator").value = "+";
        } else if (val == "subtract"){
        document.getElementById("operator").value = "-";
        } else if (val == "multiply"){
        document.getElementById("operator").value = "*";
        } else if (val == "divide"){
        document.getElementById("operator").value = "/"; 
        }
}
</script>

</body>
</html>

You were close with your loop but only saw one symbol because of missing instructions. As @ScottMarucs pointed out, don't forget the closing bracket.

Answer №5

Feel free to verify this as well. It's essentially the same code with some minor tweaks

function displayOptr(i) {
    var optrArr =["+","-","*","/"];
   if (i==0){
       document.getElementById("operator").value = "+";
     } else if (i==1){
       document.getElementById("operator").value = "-";
     } else if (i==2){
       document.getElementById("operator").value = "*";
     } else if (i==3){
       document.getElementById("operator").value = "/";
     }                
}
<div class="leftDiv">
    <div id="colorblock">
        <div id = "add" class = "blocks" onclick="displayOptr(0)">ADD</div>
    <div id = "subtract" onclick="displayOptr(1)" class = "blocks">SUBTRACT</div>
    <div id = "multiply" onclick="displayOptr(2)" class = "blocks">MULTIPLY</div>
    <div id = "divide" onclick="displayOptr(3)" class = "blocks">DIVIDE</div>
    </div>
</div>
    <input type = "text" size="1" id = "operator">

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

What is the best way to create 7 or 8 column grids with Vuetify's v-row and v-col components?

I understand that vuetify's grid system is based on a 12-column flex-box layout, but I would like to customize it to have 7 or 8 columns by default instead of the usual 12. In the code snippet below, you can see my attempt: <v-row> <v-col ...

Leveraging JavaScript functions for invoking Ajax requests, accompanied by ASP.NET controls

Having a background in PHP, I am accustomed to using a PHP file to handle all of my ajax calls. Recently, I have been introduced to ASP.NET controls and the overall environment. I am curious about the correct method for handling ajax requests when they n ...

What causes the border to trigger the appearance of a scrollbar due to an overflow?

The first image display a scrollbar, while the second one does not. It all comes down to the .tabulator CSS class and specifically the border property. How come only a 1px border impacts the scroll feature instead of affecting the entire content? https: ...

What is the best way to delete a model from a Backbone.Collection?

How can I properly remove a model from a collection in Backbone.js? var item = new Backbone.Model({ id: "01", someValue: "blabla", someOtherValue: "boa" }); var list = new Backbone.Collection([item]); list.get("01").destroy(); After calling ...

Using jQuery to set the background-image on the body's after pseudo-element with CSS

I am currently utilizing body:after for setting the page wallpaper. body:after { background-image: url('assets/img/wallpapers/<?php echo $getWallpaperFile; ?>'); } CSS content: ' '; display: block; position: absolute; left: ...

Vue js is throwing an error message that says "Reading 'push' property of undefined is not possible"

I've encountered an issue while trying to navigate to other routes. The error I'm receiving is: Uncaught (in promise) TypeError: Cannot read properties of undefined (reading 'push') at eval (JoinRoom.vue?bd9d:74:1) This is how I pu ...

Increase the background image size for a <li> element

I am working with an unordered list and have set it up to display a background image on the li element when the cursor hovers over it: <div class="sidebar"> <ul> <li>test</li> <li>test</li> ...

Launch a new tab within the parent window, passing on variables from the parent window

Currently, I have a button that opens a new window in a new tab by using window.open("newpage.html"). In the child window, I use childVar = window.opener.parentGlobalVar to access global variables from the parent window. Now, I have been requested to open ...

Tips for ensuring Accordion menu closes upon clicking a second time

I created a basic Accordion menu using just HTML and CSS. The functionality works well, but I'm facing an issue where clicking on an open accordion doesn't close it. Can this be achieved with CSS alone or would I need to use JavaScript? .midd ...

Looking for JavaScript code that can dynamically create an HTML table from JSON data

I am in need of a javascript solution that can dynamically generate either an HTML table or a bootstrap grid layout based on a specific data structure. [ {"x":0,"y":0,"width":2,"height":1,"title":"Lorem ipsum dolor sit amet"}, {"x":2,"y":0,"width ...

The function "toggleHeightAndOpacity" cannot be accessed on this object because it is not defined

I'm attempting to invoke a variable function name, a task I have successfully accomplished many times in the past using code similar to that found here. <script type="text/javascript"> $.fn.toggleHeightAndOpacity = function(show) { ...

Using React components with Material UI to create styled div boxes

As I work on creating a mock website with React and Material UI, I have utilized the RaisedButtonExampleSimple component for buttons from Material UI within a div named App-Intro. Strangely, the text in the Div "Customer-Choice" is displaying above the but ...

Tips for combining text and an unordered list on the same line:

I attempted to align them in a single line, but they are not cooperating. The text floating to the left looks fine, however, the list that floats to the right is causing issues. I tried various methods to make them display inline, but they still appear sli ...

What is the proper way to invoke a variable-function in Node.js?

I have a function called `findPeopleByName` that queries the database for a specific username, but I'm not sure how to call it in my Node.js code. Here's what I have so far: // Retrieve user_name from POST request. app.post("/api/exercise/new-u ...

How can you use a single parameter in a JavaScript function to swap the values of two numbers

Here's the challenge I'm facing: I need to create a function that will output 5 when given a(0), and 0 when given a(5). a(0) = 5 a(5) = 0 It should look like this: Hint: Use the following function structure function A(num){} something ...

The sticky navbar fails to stay in place when the content becomes too lengthy

This is my current state of code (minified, for explanation only) index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-w ...

Modifying CSS Styles using JQuery

I've been attempting to use JQuery to change a CSS property without success, despite trying multiple solutions found on SO. Here's what I've attempted (with numberHours being a previously defined variable): $(".cd-schedule .events .top-inf ...

What is the best way to add an ellipsis to the conclusion of a paragraph using .dotdotdot?

I'm struggling with implementing the ellipsis function on my website. My goal is to have the ellipsis appear at the end of each paragraph in the news_inner div (morgan, pia, and gold). I found the function on , but I'm having difficulty understan ...

if the current value in the field surpasses the specified value in JavaScript

Looking to incorporate an additional condition into a JavaScript function initial condition if (content.length==elmnt.maxLength) new condition if (content.length==elmnt.maxLength && current form field value > 1400) How can I properly implement the ...

Ensuring Secure API Request Distribution

Currently, I am experimenting with distributed API requests. In PHP, I am developing a website that allows users to make requests on behalf of the server. The objective is to distribute these requests among users to maintain scalability even in high-traffi ...